Repository navigation
feat(sql-contract-psl): close PSL-TS contract parity gaps - #229
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:
📝 WalkthroughWalkthroughThis pull request implements ADR 170: Parameterized Native Types in Contracts, where parameterized storage types now store the base native type name separately from parameters. Type expansion is refactored from centralized logic to codec-hook-driven expansion, contract source providers accept a context parameter with composed extension packs, and contract enrichment merges framework capabilities with extension metadata. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes The changes span multiple architectural layers (contract authoring, type expansion, migration planning, extension system) with dense logic around codec hooks and contract enrichment. While there is repetition in test fixture updates, the heterogeneous nature of edits across contract source providers, the planner, adapters, and extensions demands careful review of integration points and hook wiring. Approximately 70+ affected files with significant logic modifications. Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
@prisma-next/runtime-executor
@prisma-next/sql-runtime
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/contract-authoring
@prisma-next/contract-ts
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/cli
@prisma-next/emitter
@prisma-next/eslint-plugin
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@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/family-sql
@prisma-next/sql-kysely-lane
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-lane
@prisma-next/target-postgres
@prisma-next/adapter-postgres
@prisma-next/driver-postgres
@prisma-next/core-control-plane
@prisma-next/core-execution-plane
@prisma-next/config
@prisma-next/contract
@prisma-next/operations
@prisma-next/plan
@prisma-next/utils
commit: |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (6)
docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md (1)
45-45: Use the canonical architectural term for control-plane ownership.Consider replacing “composed framework components” with “SQL family instance” to match established architecture vocabulary and reduce ambiguity.
Suggested wording tweak
-- Where schema verification is codec-hook driven, parameterized type expansion should be provided via control-plane codec hooks on the composed framework components. +- Where schema verification is codec-hook driven, parameterized type expansion should be provided via control-plane codec hooks on the SQL family instance.Based on learnings: preserve the domain-specific term "SQL family instance" when referring to an instantiated SqlControlFamilyInstance that provides control-plane operations.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in contracts.md at line 45, Replace the ambiguous phrase "composed framework components" with the canonical term "SQL family instance" throughout the sentence and any related text so the document consistently refers to an instantiated SqlControlFamilyInstance that provides control-plane operations; update the sentence currently reading "Where schema verification is codec-hook driven, parameterized type expansion should be provided via control-plane codec hooks on the composed framework components." to use "SQL family instance" and ensure any nearby references or examples that imply control-plane ownership reference SqlControlFamilyInstance explicitly.test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts (2)
48-58: UseifDefined()for conditional spread fields.The inline
...(cond ? { ... } : {})patterns here should be converted toifDefined()for consistency with repo conventions.
As per coding guidelines, "{packages,examples,test}/**/*.{ts,tsx}: UseifDefined()from@prisma-next/utils/definedfor conditional object spreads instead of inline conditional spread patterns."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts` around lines 48 - 58, Replace the inline conditional object spreads for descriptor['capabilities'] and types.codecTypes with the repo's ifDefined helper: import ifDefined from '@prisma-next/utils/defined' (or use existing import) and change the two occurrences where code uses "...(descriptor['capabilities'] ? { capabilities: descriptor['capabilities'] } : {})" and the nested "...(types ? { types: { ... } } : {})" / "codecTypes ? { ...codecTypes, controlPlaneHooks: undefined } : undefined" to use ifDefined(...) so the object uses ifDefined(descriptor['capabilities'], value => ({ capabilities: value })) and similarly wrap types and codecTypes with ifDefined to produce the same conditional spreads consistently.
95-96: Avoid the force-cast onresult.valueat Line 95.Prefer a type-guarded path (
isPlainObject) to extractcapabilitiesinstead ofascasting.
As per coding guidelines, "**/*.{ts,tsx}: Replace blind casts with type predicates instead ofascasts."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts` around lines 95 - 96, Replace the blind cast on result.value when reading capabilities with a type-guarded extraction: use the isPlainObject predicate to check result.value, confirm it has a capabilities key, and only then read and assign capabilities as a Record<string, unknown>; otherwise fallback to {}. Update the code around result.value and capabilities to import/use isPlainObject, perform the guard (e.g. if (isPlainObject(result.value) && 'capabilities' in result.value) …), and remove the force-cast so capabilities is safely typed without using as on result.value.test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts (2)
9-39: Consider sharingextensionPackMetaFromDescriptoracross parity templates.This helper now duplicates the same transformation logic used in
test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts(Lines 31-60), which can drift over time.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts` around lines 9 - 39, Duplicate helper extensionPackMetaFromDescriptor is present in multiple parity templates; extract it into a single shared utility and import it from both templates to avoid drift. Create a shared module exporting extensionPackMetaFromDescriptor (preserving its signature and behavior, including the types/codecTypes handling and the controlPlaneHooks removal), replace the local implementation in prisma-next.config.parity-psl.ts and prisma-next.config.parity-ts.ts with an import and use the shared function, and update any exports/typing so both templates compile unchanged.
27-38: Switch inline conditional spreads toifDefined().Both metadata shaping and conditional contract-option injection use spread ternaries that should follow the repo’s
ifDefined()convention.
As per coding guidelines, "{packages,examples,test}/**/*.{ts,tsx}: UseifDefined()from@prisma-next/utils/definedfor conditional object spreads instead of inline conditional spread patterns."Also applies to: 54-59
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts` around lines 27 - 38, Replace the inline conditional spread patterns with the project's ifDefined() helper from `@prisma-next/utils/defined`: instead of using ...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and the ternary around types/codecTypes, call ifDefined(record['capabilities'], v => ({ capabilities: v })) and ifDefined(types, t => ({ types: { ...t, codecTypes: t.codecTypes ? { ...t.codecTypes, controlPlaneHooks: undefined } : undefined }})); apply the same ifDefined transformation to the similar block at lines referenced (54-59) so all conditional object spreads follow the repo convention.examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts (1)
10-18: Prefer VitestexpectTypeOfmatchers over localEqual/Expect/NotNeverhelpers in*.test.ts.This keeps type tests consistent with the repo standard and avoids duplicated custom type-assertion utilities.
♻️ Proposed refactor
-import { test } from 'vitest'; +import { expectTypeOf, test } from 'vitest'; @@ -type Equal<A, B> = - (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false; -type Expect<T extends true> = T; type NotNever<T> = [T] extends [never] ? false : true; @@ - // Compile-time assertions - type Assertions = [ - Expect<Equal<Row['embedding'], Vector<1536> | null>>, - Expect<Equal<Row['id'], Char<36>>>, - Expect<Equal<Row['title'], string>>, - Expect<Equal<Row['userId'], string>>, - Expect<NotNever<Row['createdAt']>>, - ]; - const assertions = null as unknown as Assertions; - void assertions; + expectTypeOf<Row['embedding']>().toEqualTypeOf<Vector<1536> | null>(); + expectTypeOf<Row['id']>().toEqualTypeOf<Char<36>>(); + expectTypeOf<Row['title']>().toEqualTypeOf<string>(); + expectTypeOf<Row['userId']>().toEqualTypeOf<string>(); + type CreatedAtIsNotNever = NotNever<Row['createdAt']>; + expectTypeOf<CreatedAtIsNotNever>().toEqualTypeOf<true>();As per coding guidelines:
**/*.{test,spec}.{ts,tsx}: “Use type test patterns with vitest; preferexpectTypeOffor type assertions.”Also applies to: 46-55
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts` around lines 10 - 18, Replace the local type-assertion helpers Equal, Expect, and NotNever in get-user-posts.types.test.ts with Vitest's expectTypeOf matchers: locate the type helpers (Equal, Expect, NotNever) and any assertions that use them, then convert those assertions to use expectTypeOf<typeof SomeType>().toEqualTypeOf<OtherType>() or expectTypeOf<T>().not.toBeNever() / .toBeNever() equivalents; ensure imports use Vitest's expectTypeOf and remove the now-unused helper type declarations (Equal, Expect, NotNever).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@examples/prisma-next-demo/src/queries/similarity-search.test-d.ts`:
- Around line 8-13: The file defines custom type helpers Equal and Expect;
replace this pattern with Vitest's built-in expectTypeOf: remove the type
aliases Equal and Expect and add an import for expectTypeOf from 'vitest', then
rewrite any assertions that used Expect<Equal<...>> to use
expectTypeOf(...).toMatchTypeOf(...) or the appropriate expectTypeOf matcher
against the subject (e.g., db or specific types used in the test). Update
occurrences referencing Equal or Expect accordingly (search for the symbols
Equal and Expect and replace those assertions with expectTypeOf-based calls).
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 1028-1040: The code currently parses constraintNameRaw into
constraintName for all relation attributes (constraintNameRaw, constraintName,
parseQuotedStringLiteral) but never errors when a map is supplied on a
backrelation-list field (the backrelation-list validation branch), causing a
silent no-op; update the backrelation-list validation branch to check if
constraintNameRaw is present and, if so, push the same
PSL_INVALID_RELATION_ATTRIBUTE diagnostic (with the same message and span using
input.modelName, input.fieldName, input.sourceId, input.attribute.span) and
return undefined so that `@relation`(map: ...) on list-side backrelations is
rejected; apply the same guard for the other occurrence around 1080-1085.
In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Line 300: Replace the unsafe cast 'sha256:profile' as never with the typed
constructor call profileHash('sha256:profile'); update the object property
currently set to "profileHash: 'sha256:profile' as never" to "profileHash:
profileHash('sha256:profile')" using the imported profileHash function so the
value is properly typed and consistent with other tests.
In `@test/integration/test/authoring/psl.pgvector-dbinit.test.ts`:
- Around line 1-3: The test imports join from 'node:path' but the repo
standardizes on 'pathe'; replace the import of join so it comes from 'pathe'
instead of 'node:path' (i.e., change "import { join } from 'node:path';" to
"import { join } from 'pathe';") while leaving the other fs imports (existsSync,
rmSync, writeFileSync) and the postgresAdapter import untouched so path
utilities use pathe's cross-runtime behavior.
- Around line 71-100: The test uses withDevDatabase (pglite) which lacks
pgvector extension support; replace the test harness so the DDL in
client.dbInit({ mode: 'apply' }) runs against a real PostgreSQL instance that
supports extensions. Concretely, swap out withDevDatabase(...) for your
real-Postgres test helper (e.g., withPostgresDatabase or the project’s real-DB
fixture) that yields a connectionString to a PostgreSQL server with extension
installation privileges, keep createControlClient(...) and the dbInit calls
(plan and apply) as-is, and ensure the test setup/teardown provisions that the
pgvector extension is available before running client.dbInit({ mode: 'apply' }).
---
Nitpick comments:
In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md:
- Line 45: Replace the ambiguous phrase "composed framework components" with the
canonical term "SQL family instance" throughout the sentence and any related
text so the document consistently refers to an instantiated
SqlControlFamilyInstance that provides control-plane operations; update the
sentence currently reading "Where schema verification is codec-hook driven,
parameterized type expansion should be provided via control-plane codec hooks on
the composed framework components." to use "SQL family instance" and ensure any
nearby references or examples that imply control-plane ownership reference
SqlControlFamilyInstance explicitly.
In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts`:
- Around line 10-18: Replace the local type-assertion helpers Equal, Expect, and
NotNever in get-user-posts.types.test.ts with Vitest's expectTypeOf matchers:
locate the type helpers (Equal, Expect, NotNever) and any assertions that use
them, then convert those assertions to use expectTypeOf<typeof
SomeType>().toEqualTypeOf<OtherType>() or expectTypeOf<T>().not.toBeNever() /
.toBeNever() equivalents; ensure imports use Vitest's expectTypeOf and remove
the now-unused helper type declarations (Equal, Expect, NotNever).
In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts`:
- Around line 9-39: Duplicate helper extensionPackMetaFromDescriptor is present
in multiple parity templates; extract it into a single shared utility and import
it from both templates to avoid drift. Create a shared module exporting
extensionPackMetaFromDescriptor (preserving its signature and behavior,
including the types/codecTypes handling and the controlPlaneHooks removal),
replace the local implementation in prisma-next.config.parity-psl.ts and
prisma-next.config.parity-ts.ts with an import and use the shared function, and
update any exports/typing so both templates compile unchanged.
- Around line 27-38: Replace the inline conditional spread patterns with the
project's ifDefined() helper from `@prisma-next/utils/defined`: instead of using
...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and
the ternary around types/codecTypes, call ifDefined(record['capabilities'], v =>
({ capabilities: v })) and ifDefined(types, t => ({ types: { ...t, codecTypes:
t.codecTypes ? { ...t.codecTypes, controlPlaneHooks: undefined } : undefined
}})); apply the same ifDefined transformation to the similar block at lines
referenced (54-59) so all conditional object spreads follow the repo convention.
In `@test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts`:
- Around line 48-58: Replace the inline conditional object spreads for
descriptor['capabilities'] and types.codecTypes with the repo's ifDefined
helper: import ifDefined from '@prisma-next/utils/defined' (or use existing
import) and change the two occurrences where code uses
"...(descriptor['capabilities'] ? { capabilities: descriptor['capabilities'] } :
{})" and the nested "...(types ? { types: { ... } } : {})" / "codecTypes ? {
...codecTypes, controlPlaneHooks: undefined } : undefined" to use ifDefined(...)
so the object uses ifDefined(descriptor['capabilities'], value => ({
capabilities: value })) and similarly wrap types and codecTypes with ifDefined
to produce the same conditional spreads consistently.
- Around line 95-96: Replace the blind cast on result.value when reading
capabilities with a type-guarded extraction: use the isPlainObject predicate to
check result.value, confirm it has a capabilities key, and only then read and
assign capabilities as a Record<string, unknown>; otherwise fallback to {}.
Update the code around result.value and capabilities to import/use
isPlainObject, perform the guard (e.g. if (isPlainObject(result.value) &&
'capabilities' in result.value) …), and remove the force-cast so capabilities is
safely typed without using as on result.value.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: de947a95-ff66-4b8e-924d-708e4e6dbb76
⛔ Files ignored due to path filters (6)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.mdis excluded by!projects/**projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/code-review.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/system-design-review.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/walkthrough.mdis excluded by!projects/**
📒 Files selected for processing (33)
docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.mdexamples/prisma-next-demo/README.mdexamples/prisma-next-demo/package.jsonexamples/prisma-next-demo/prisma-next.config.tsexamples/prisma-next-demo/prisma-next.config.ts-contract.tsexamples/prisma-next-demo/prisma/schema.prismaexamples/prisma-next-demo/src/prisma-no-emit/context.tsexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/src/queries/get-user-posts.types.test.tsexamples/prisma-next-demo/src/queries/similarity-search.test-d.tsexamples/prisma-next-demo/src/queries/similarity-search.tsexamples/prisma-next-demo/src/queries/similarity-search.types.test.tsexamples/prisma-next-demo/test/utils/control-client.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/3-extensions/pgvector/src/exports/column-types.tspackages/3-extensions/pgvector/src/exports/control.tspackages/3-extensions/pgvector/test/column-types.test.tspackages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.tspackages/3-targets/6-adapters/postgres/src/core/parameterized-types.tspackages/3-targets/6-adapters/postgres/test/parameterized-types.test.tstest/integration/test/authoring/parity/map-attributes/contract.tstest/integration/test/authoring/parity/map-attributes/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/schema.prismatest/integration/test/authoring/parity/pgvector-named-type/contract.tstest/integration/test/authoring/parity/pgvector-named-type/expected.contract.jsontest/integration/test/authoring/psl.pgvector-dbinit.test.tstest/integration/test/authoring/templates/prisma-next.config.parity-psl.tstest/integration/test/authoring/templates/prisma-next.config.parity-ts.ts
783f828 to
e383b36
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (1)
1028-1040:⚠️ Potential issue | 🟡 MinorReject
@relation(map: ...)on backrelation-list fields to avoid silent no-op.
mapis now parsed intoconstraintName, but list-side backrelations still only rejectfields/referencesandonDelete/onUpdate. This allows invalid list-sidemapusage to pass silently and then be ignored.🐛 Suggested guard in backrelation-list validation branch
if (parsedRelation.onDelete || parsedRelation.onUpdate) { diagnostics.push({ code: 'PSL_INVALID_RELATION_ATTRIBUTE', message: `Backrelation list field "${model.name}.${field.name}" cannot declare onDelete/onUpdate; define referential actions on the FK-side relation field`, sourceId, span: relationAttribute.span, }); continue; } + if (parsedRelation.constraintName) { + diagnostics.push({ + code: 'PSL_INVALID_RELATION_ATTRIBUTE', + message: `Backrelation list field "${model.name}.${field.name}" cannot declare map; define FK constraint names on the FK-side relation field`, + sourceId, + span: relationAttribute.span, + }); + continue; + } relationName = parsedRelation.relationName;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 1028 - 1040, The backrelation-list validation branch currently rejects only fields/references and onDelete/onUpdate but misses rejecting a `map` argument, so add a guard that treats a non-empty `constraintNameRaw` (and thus `constraintName`) as invalid on list-side backrelations: in the backrelation-list validation code path (the branch that already pushes diagnostics for fields/references and onDelete/onUpdate), check `if (constraintNameRaw)` and push a diagnostic with code 'PSL_INVALID_RELATION_ATTRIBUTE' and the same message pattern used above (`Relation field "${input.modelName}.${input.fieldName}" map argument must be a quoted string literal` or appropriate text rejecting map usage), then return undefined—using the existing `input`, `constraintNameRaw`, `constraintName`, `input.diagnostics`, and `input.attribute.span` symbols to implement the check.
🧹 Nitpick comments (5)
packages/3-extensions/pgvector/src/exports/control.ts (1)
74-82: Preserve existingcontrolPlaneHooksentries when extending the map.Line 78 currently replaces the full
controlPlaneHooksobject. Merging existing entries first avoids accidentally dropping hooks ifpgvectorPackMeta.types.codecTypes.controlPlaneHooksgrows later.Proposed diff
types: { ...pgvectorPackMeta.types, codecTypes: { ...pgvectorPackMeta.types.codecTypes, controlPlaneHooks: { + ...(pgvectorPackMeta.types.codecTypes.controlPlaneHooks ?? {}), [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks, }, }, },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/pgvector/src/exports/control.ts` around lines 74 - 82, The code currently overwrites pgvectorPackMeta.types.codecTypes.controlPlaneHooks instead of merging new entries; update the build of types.codecTypes.controlPlaneHooks to spread the existing pgvectorPackMeta.types.codecTypes.controlPlaneHooks first and then add the new entry [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so existing hooks are preserved (reference symbols: pgvectorPackMeta.types.codecTypes.controlPlaneHooks, PGVECTOR_CODEC_ID, vectorControlPlaneHooks).packages/2-sql/2-authoring/contract-psl/src/provider.ts (1)
181-194: ValidateextensionPackspayloads before emitting merged contract output.
extensionPacksis merged asRecord<string, unknown>with no JSON-shape guard. If a non-serializable value slips in, emitted metadata can degrade silently.Proposed hardening
+function isJsonValue(value: unknown): boolean { + if (value === null) return true; + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return true; + if (Array.isArray(value)) return value.every(isJsonValue); + if (!isPlainObject(value)) return false; + return Object.values(value).every(isJsonValue); +} + const extensionPacks = options?.extensionPacks ? mergePlainObjects(interpreted.value.extensionPacks, options.extensionPacks) : interpreted.value.extensionPacks; + + if (!isJsonValue(extensionPacks)) { + return notOk({ + summary: 'Invalid extensionPacks payload: value must be JSON-serializable', + diagnostics: [{ code: 'PSL_EXTENSION_PACKS_INVALID', message: 'Non-JSON value found in extensionPacks' }], + meta: { schemaPath }, + }); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts` around lines 181 - 194, The merged extensionPacks currently accepts any Record<string, unknown> and can silently include non-serializable values; before merging/interpolating extensionPacks (the logic around interpreted.value.extensionPacks, options.extensionPacks, mergePlainObjects, and the final sortDeepTyped call), validate each entry is JSON-serializable (or matches the expected plain-JSON shape) and either reject or filter out invalid entries and log/return an error via the ok/err flow; implement a small guard (e.g., isJsonSerializable/isPlainJson) and apply it to options.extensionPacks and interpreted.value.extensionPacks prior to mergePlainObjects so the returned object only contains safe, serializable payloads.test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts (1)
27-37: Replace inline conditional spreads withifDefined()for consistency.These new spreads use
...(cond ? { ... } : {}). In this repo, conditional properties should useifDefined()in TypeScript files undertest/**.♻️ Proposed refactor
+import { ifDefined } from '@prisma-next/utils/defined'; + function extensionPackMetaFromDescriptor(descriptor: unknown): Record<string, unknown> { @@ return { kind: record['kind'], id: record['id'], familyId: record['familyId'], targetId: record['targetId'], version: record['version'], - ...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}), - ...(types - ? { - types: { - ...types, - codecTypes: types.codecTypes - ? { ...types.codecTypes, controlPlaneHooks: undefined } - : undefined, - }, - } - : {}), + ...ifDefined('capabilities', record['capabilities']), + ...ifDefined( + 'types', + types + ? { + ...types, + ...ifDefined( + 'codecTypes', + types.codecTypes + ? { ...types.codecTypes, controlPlaneHooks: undefined } + : undefined, + ), + } + : undefined, + ), }; } @@ contract: prismaContract('./schema.prisma', { output: 'output/contract.json', composedExtensionPacks: extensionPacks.map((pack) => pack.id), - ...(extensionPacks.length > 0 - ? { - extensionPacks: extensionPacksMeta, - capabilitySources: [postgresAdapter, ...Object.values(extensionPacksMeta)], - } - : {}), + ...ifDefined('extensionPacks', extensionPacks.length > 0 ? extensionPacksMeta : undefined), + ...ifDefined( + 'capabilitySources', + extensionPacks.length > 0 ? [postgresAdapter, ...Object.values(extensionPacksMeta)] : undefined, + ), }), });As per coding guidelines, "Use
ifDefined()from@prisma-next/utils/definedfor conditional object spreads instead of inline conditional spread patterns".Also applies to: 54-59
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts` around lines 27 - 37, Replace the inline conditional spreads like ...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and the types block using ...(types ? { types: { ... } } : {}) with the repo-standard ifDefined() helper from `@prisma-next/utils/defined`; specifically, import ifDefined and wrap conditional properties (capabilities, types, and nested codecTypes controlPlaneHooks removal) with ifDefined(...) so the object construction uses ifDefined(record['capabilities'], ...) and ifDefined(types, ...) (and handle codecTypes similarly) instead of ternary spread expressions to match test/** TypeScript conventions.examples/prisma-next-demo/src/queries/similarity-search.types.test.ts (1)
9-15: PreferexpectTypeOfover customEqual/Expecthelpers for type assertions in this test.Using Vitest’s built-in matcher API keeps type tests consistent and removes local helper maintenance.
♻️ Proposed refactor
-import { test } from 'vitest'; +import { expectTypeOf, test } from 'vitest'; ... -type Equal<A, B> = - (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false; -type Expect<T extends true> = T; ... - // Compile-time assertions - type Assertions = [ - Expect<Equal<Row['distance'], number>>, - Expect<Equal<Row['id'], Char<36>>>, - Expect<Equal<Row['title'], string>>, - ]; - const assertions = null as unknown as Assertions; - void assertions; + expectTypeOf<Row['distance']>().toEqualTypeOf<number>(); + expectTypeOf<Row['id']>().toEqualTypeOf<Char<36>>(); + expectTypeOf<Row['title']>().toEqualTypeOf<string>();As per coding guidelines:
**/*.{test,spec}.{ts,tsx}: “Use type test patterns with vitest; preferexpectTypeOffor type assertions.”Also applies to: 46-53
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/src/queries/similarity-search.types.test.ts` around lines 9 - 15, This test file defines local type helpers Equal and Expect for type assertions; replace them with Vitest's built-in expectTypeOf to follow project guidelines: remove the custom type helpers (Equal, Expect) and instead import and use expectTypeOf from 'vitest' in the tests (e.g., use expectTypeOf<Actual>().toEqualTypeOf<Expected>() or other expectTypeOf matchers) so the type assertions in similarity-search.types.test.ts use Vitest's matcher API consistently.examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts (1)
10-17: UseexpectTypeOffor these type assertions instead of custom helper types.This keeps type tests aligned with the project’s Vitest-based assertion pattern and avoids custom assertion utilities.
♻️ Proposed refactor
-import { test } from 'vitest'; +import { expectTypeOf, test } from 'vitest'; ... -type Equal<A, B> = - (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false; -type Expect<T extends true> = T; -type NotNever<T> = [T] extends [never] ? false : true; ... - // Compile-time assertions - type Assertions = [ - Expect<Equal<Row['embedding'], Vector<1536> | null>>, - Expect<Equal<Row['id'], Char<36>>>, - Expect<Equal<Row['title'], string>>, - Expect<Equal<Row['userId'], string>>, - Expect<NotNever<Row['createdAt']>>, - ]; - const assertions = null as unknown as Assertions; - void assertions; + expectTypeOf<Row['embedding']>().toEqualTypeOf<Vector<1536> | null>(); + expectTypeOf<Row['id']>().toEqualTypeOf<Char<36>>(); + expectTypeOf<Row['title']>().toEqualTypeOf<string>(); + expectTypeOf<Row['userId']>().toEqualTypeOf<string>(); + expectTypeOf<Row['createdAt']>().not.toEqualTypeOf<never>();As per coding guidelines:
**/*.{test,spec}.{ts,tsx}: “Use type test patterns with vitest; preferexpectTypeOffor type assertions.”Also applies to: 46-55
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts` around lines 10 - 17, The test file defines custom type helpers (Equal, Expect, NotNever) for type assertions; replace these with Vitest's expectTypeOf by importing expectTypeOf from 'vitest' and converting each assertion: use expectTypeOf<Actual>().toEqualTypeOf<Expected>() in place of Equal/Expect patterns and use expectTypeOf<Actual>().not.toBeNever() instead of NotNever; remove the Equal/Expect/NotNever type aliases and update all occurrences (including the other block around lines 46-55) to the new expectTypeOf calls so the file follows the project's Vitest type-test pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 1028-1040: The backrelation-list validation branch currently
rejects only fields/references and onDelete/onUpdate but misses rejecting a
`map` argument, so add a guard that treats a non-empty `constraintNameRaw` (and
thus `constraintName`) as invalid on list-side backrelations: in the
backrelation-list validation code path (the branch that already pushes
diagnostics for fields/references and onDelete/onUpdate), check `if
(constraintNameRaw)` and push a diagnostic with code
'PSL_INVALID_RELATION_ATTRIBUTE' and the same message pattern used above
(`Relation field "${input.modelName}.${input.fieldName}" map argument must be a
quoted string literal` or appropriate text rejecting map usage), then return
undefined—using the existing `input`, `constraintNameRaw`, `constraintName`,
`input.diagnostics`, and `input.attribute.span` symbols to implement the check.
---
Nitpick comments:
In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts`:
- Around line 10-17: The test file defines custom type helpers (Equal, Expect,
NotNever) for type assertions; replace these with Vitest's expectTypeOf by
importing expectTypeOf from 'vitest' and converting each assertion: use
expectTypeOf<Actual>().toEqualTypeOf<Expected>() in place of Equal/Expect
patterns and use expectTypeOf<Actual>().not.toBeNever() instead of NotNever;
remove the Equal/Expect/NotNever type aliases and update all occurrences
(including the other block around lines 46-55) to the new expectTypeOf calls so
the file follows the project's Vitest type-test pattern.
In `@examples/prisma-next-demo/src/queries/similarity-search.types.test.ts`:
- Around line 9-15: This test file defines local type helpers Equal and Expect
for type assertions; replace them with Vitest's built-in expectTypeOf to follow
project guidelines: remove the custom type helpers (Equal, Expect) and instead
import and use expectTypeOf from 'vitest' in the tests (e.g., use
expectTypeOf<Actual>().toEqualTypeOf<Expected>() or other expectTypeOf matchers)
so the type assertions in similarity-search.types.test.ts use Vitest's matcher
API consistently.
In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts`:
- Around line 181-194: The merged extensionPacks currently accepts any
Record<string, unknown> and can silently include non-serializable values; before
merging/interpolating extensionPacks (the logic around
interpreted.value.extensionPacks, options.extensionPacks, mergePlainObjects, and
the final sortDeepTyped call), validate each entry is JSON-serializable (or
matches the expected plain-JSON shape) and either reject or filter out invalid
entries and log/return an error via the ok/err flow; implement a small guard
(e.g., isJsonSerializable/isPlainJson) and apply it to options.extensionPacks
and interpreted.value.extensionPacks prior to mergePlainObjects so the returned
object only contains safe, serializable payloads.
In `@packages/3-extensions/pgvector/src/exports/control.ts`:
- Around line 74-82: The code currently overwrites
pgvectorPackMeta.types.codecTypes.controlPlaneHooks instead of merging new
entries; update the build of types.codecTypes.controlPlaneHooks to spread the
existing pgvectorPackMeta.types.codecTypes.controlPlaneHooks first and then add
the new entry [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so existing hooks are
preserved (reference symbols:
pgvectorPackMeta.types.codecTypes.controlPlaneHooks, PGVECTOR_CODEC_ID,
vectorControlPlaneHooks).
In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts`:
- Around line 27-37: Replace the inline conditional spreads like
...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and
the types block using ...(types ? { types: { ... } } : {}) with the
repo-standard ifDefined() helper from `@prisma-next/utils/defined`; specifically,
import ifDefined and wrap conditional properties (capabilities, types, and
nested codecTypes controlPlaneHooks removal) with ifDefined(...) so the object
construction uses ifDefined(record['capabilities'], ...) and ifDefined(types,
...) (and handle codecTypes similarly) instead of ternary spread expressions to
match test/** TypeScript conventions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: de5f543f-9c52-4dae-8318-0fdc88cc2177
⛔ Files ignored due to path filters (6)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.mdis excluded by!projects/**projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/code-review.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/system-design-review.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/walkthrough.mdis excluded by!projects/**
📒 Files selected for processing (33)
docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.mdexamples/prisma-next-demo/README.mdexamples/prisma-next-demo/package.jsonexamples/prisma-next-demo/prisma-next.config.tsexamples/prisma-next-demo/prisma-next.config.ts-contract.tsexamples/prisma-next-demo/prisma/schema.prismaexamples/prisma-next-demo/src/prisma-no-emit/context.tsexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/src/queries/get-user-posts.types.test.tsexamples/prisma-next-demo/src/queries/similarity-search.test-d.tsexamples/prisma-next-demo/src/queries/similarity-search.tsexamples/prisma-next-demo/src/queries/similarity-search.types.test.tsexamples/prisma-next-demo/test/utils/control-client.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/3-extensions/pgvector/src/exports/column-types.tspackages/3-extensions/pgvector/src/exports/control.tspackages/3-extensions/pgvector/test/column-types.test.tspackages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.tspackages/3-targets/6-adapters/postgres/src/core/parameterized-types.tspackages/3-targets/6-adapters/postgres/test/parameterized-types.test.tstest/integration/test/authoring/parity/map-attributes/contract.tstest/integration/test/authoring/parity/map-attributes/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/schema.prismatest/integration/test/authoring/parity/pgvector-named-type/contract.tstest/integration/test/authoring/parity/pgvector-named-type/expected.contract.jsontest/integration/test/authoring/psl.pgvector-dbinit.test.tstest/integration/test/authoring/templates/prisma-next.config.parity-psl.tstest/integration/test/authoring/templates/prisma-next.config.parity-ts.ts
🚧 Files skipped from review as they are similar to previous changes (16)
- packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
- examples/prisma-next-demo/test/utils/control-client.ts
- packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
- examples/prisma-next-demo/package.json
- docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
- test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts
- packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
- test/integration/test/authoring/parity/map-attributes/schema.prisma
- packages/3-extensions/pgvector/test/column-types.test.ts
- packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
- packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
- examples/prisma-next-demo/src/prisma-no-emit/context.ts
- packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
- packages/3-extensions/pgvector/src/exports/column-types.ts
- test/integration/test/authoring/psl.pgvector-dbinit.test.ts
- test/integration/test/authoring/parity/map-attributes/expected.contract.json
7c52e14 to
8c431d1
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts (1)
801-825:⚠️ Potential issue | 🟠 MajorDon't silently drop declared type params when a codec hook is missing.
If
column.typeParamsis set butcodecHookshas noexpandNativeTypefor that codec, this path falls back to the barenativeType. That can emit incorrect DDL for valid contracts (vectorinstead ofvector(1536),numericinstead ofnumeric(10,2)) and hide a broken framework composition. Please fail planning here instead of degrading silently. The same guard should be mirrored inbuildNativeTypeExpander()so offlinecontractToSchema()stays aligned.As per coding guidelines, "Do not treat missing type parameters as a successful match when the contract declares them."
Also applies to: 827-846
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts` around lines 801 - 825, The code in buildColumnTypeSql currently falls back to the bare nativeType when column.typeParams are present but the codecHooks map lacks an expandNativeType hook for the codec, which silently drops declared type parameters; change buildColumnTypeSql to detect when column.typeParams is non-empty and the codecHooks entry does not provide an expandNativeType (or codecHooks has no entry) and throw/abort planning with a clear error instead of returning column.nativeType; also add the same guard in buildNativeTypeExpander so contractToSchema/offline planning fails consistently when type params are declared but no expander exists, referencing buildColumnTypeSql and buildNativeTypeExpander to locate the fixes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 61-87: The helpers (expandLength, expandPrecision, expandNumeric)
currently swallow malformed params by returning the bare nativeType; instead,
detect when a type parameter key is present but invalid and throw a clear error
so a malformed parameterized contract fails fast. Update expandLength and
expandPrecision to: if typeParams has the 'length'/'precision' key but
isValidTypeParamNumber(...) is false, throw an Error naming the nativeType and
param; otherwise behave as now. Update expandNumeric to: if 'precision' is
present and invalid throw; if 'scale' is present and invalid throw; if precision
valid and scale valid return nativeType(precision,scale); if precision valid and
scale absent return nativeType(precision); if precision absent return
nativeType.
---
Outside diff comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts`:
- Around line 801-825: The code in buildColumnTypeSql currently falls back to
the bare nativeType when column.typeParams are present but the codecHooks map
lacks an expandNativeType hook for the codec, which silently drops declared type
parameters; change buildColumnTypeSql to detect when column.typeParams is
non-empty and the codecHooks entry does not provide an expandNativeType (or
codecHooks has no entry) and throw/abort planning with a clear error instead of
returning column.nativeType; also add the same guard in buildNativeTypeExpander
so contractToSchema/offline planning fails consistently when type params are
declared but no expander exists, referencing buildColumnTypeSql and
buildNativeTypeExpander to locate the fixes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 4e4714c0-f137-41a6-81e6-5e8be8a801bb
📒 Files selected for processing (12)
docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.mdpackages/1-framework/1-core/migration/control-plane/src/migrations.tspackages/1-framework/3-tooling/cli/src/commands/migration-plan.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-reconciliation.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.tspackages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-targets/6-adapters/postgres/src/core/descriptor-meta.tspackages/3-targets/6-adapters/postgres/src/core/parameterized-types.tspackages/3-targets/6-adapters/postgres/src/exports/control.tspackages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
💤 Files with no reviewable changes (2)
- packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
- packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
- packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
- packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts (1)
144-144:⚠️ Potential issue | 🟡 MinorUse
profileHash()constructor instead ofas nevercast.The file already imports
profileHashand uses it correctly at line 21 increateTestContract. Apply the same pattern here for consistency and type safety.Suggested fix
- profileHash: 'sha256:profile' as never, + profileHash: profileHash('sha256:profile'),🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts` at line 144, Replace the unsafe cast "sha256:profile" as never with the proper constructor call using the imported profileHash function (the same pattern used in createTestContract); locate the object that sets profileHash and call profileHash('sha256:profile') to ensure consistent type safety and remove the as never cast.
🧹 Nitpick comments (4)
examples/prisma-next-demo/src/prisma-no-emit/context.ts (1)
11-11: Consider removing the inline comment.The code change is self-documenting—adding
pgvectortoextensionPacksclearly expresses the intent. The rationale ("parity with emit workflow") is better captured in the commit message or PR description than in an inline comment that will remain after the context is forgotten.As per coding guidelines: "Don't add comments if avoidable; prefer code which expresses its intent."
🔧 Suggested diff
-// pgvector was previously missing here; added for parity with the emit workflow config. export const stack = createSqlExecutionStack({🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts` at line 11, Remove the inline comment that explains why pgvector was added—since the change is self-explanatory by adding "pgvector" to extensionPacks, delete the comment line in the same file so only the code (the extensionPacks array containing "pgvector") remains; retain the change itself and move any rationale into the PR/commit message instead.packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts (1)
10-24: Consider using a well-established library for deep merging.This custom
mergePlainObjectsimplementation handles basic nested object merging. While functional, using a battle-tested library like Lodash'smergeormergeWithwould provide more robust handling of edge cases and reduce maintenance burden.However, if bundle size is a concern and this simple merge suffices for the known use cases, the current implementation is acceptable.
Based on learnings: "In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts` around lines 10 - 24, Replace the custom deep-merge in mergePlainObjects with a well-tested utility: remove or stop using the mergePlainObjects function and instead import and call a battle-tested deep merge (e.g., lodash.merge or lodash.mergeWith) wherever mergePlainObjects is used; if bundle size is a concern, explicitly document the limited behavior of mergePlainObjects and add unit tests covering edge cases (arrays, non-plain objects, prototypes) and a TODO to switch to lodash.merge when acceptable. Ensure references to mergePlainObjects in this module are updated to use the chosen merge function and keep the same return shape (Record<string, unknown>).packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts (1)
78-78: Consider splitting this test file in a follow-up.At 694 lines, the file exceeds the 500-line guideline. The distinct
describeblocks (empty database, composite unique, column defaults) could be split into separate files likeplanner.empty-db.test.ts,planner.unique-constraints.test.ts, andplanner.defaults.test.ts.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts` at line 78, The file is too large and should be split by the major describe blocks: extract the "PostgresMigrationPlanner - when database is empty" suite into a new planner.empty-db.test.ts, move the "composite unique" suite into planner.unique-constraints.test.ts, and move the "column defaults" suite into planner.defaults.test.ts; when splitting, preserve each describe(...) block and its contained tests, update/retain any shared helper imports (e.g., setup/teardown helpers, factory functions) at the top of each new file, ensure exported/used symbols like PostgresMigrationPlanner or helper functions remain imported from their original modules, and run the test runner to confirm no missing imports or duplicated globals.packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts (1)
5-6: Derive the hook types from the source instead of redefining them locally.
ExpandFn/HooksMapwiden the real descriptor surface here, and theRecord<string, ...>cast drops literal-key typing. That makes this test less effective at catching renamed codec IDs or hook-signature drift. Prefertypeof postgresAdapterDescriptorMeta.types.codecTypes.controlPlaneHooksor an exported hook/input type from the source module.Also applies to: 105-105
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts` around lines 5 - 6, Replace the local redefinitions ExpandFn and HooksMap with types derived from the source so they track real descriptor shapes: import or reference typeof postgresAdapterDescriptorMeta.types.codecTypes.controlPlaneHooks (or the exported hook/input type) and use that instead of Record<string,...>/manual function type; update any usages (including the other occurrence around the block that starts near line 105) to use the derived type so literal keys and signatures are preserved and tests will catch renames/signature drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts`:
- Around line 823-824: The current code lets renderParameterizedTypeSql(column,
codecHooks) fall back to column.nativeType, which silently drops declared type
parameters; instead, when renderParameterizedTypeSql returns null/undefined
(i.e., codec hook missing), fail planning by throwing an error or asserting—do
this in the same spot where assertSafeNativeType(column.nativeType) is called.
Replace the fallback return of column.nativeType with a clear failure that
references the column (e.g., column.name/type) and mentions the missing codec
hook in codecHooks so the migration fails rather than emitting an
unparameterized native type; apply the same change to the other occurrences in
the block handling renderParameterizedTypeSql (the 827–842 region).
In `@packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts`:
- Around line 107-197: The tests currently only exercise one codec key per block
(e.g. hooks['sql/char@1'], hooks['pg/timestamp@1'], hooks['pg/numeric@1']) —
convert each block to table-driven tests that iterate over every advertised
codec id for that family and run the same assertions against
hooks[<codecId>]!.expandNativeType; specifically, for expandLength iterate ids
['sql/char@1','sql/varchar@1','pg/char@1','pg/varchar@1','pg/bit@1','pg/varbit@1'],
for expandPrecision iterate
['pg/timestamp@1','pg/timestamptz@1','pg/time@1','pg/timetz@1','pg/interval@1'],
and keep expandNumeric using hooks['pg/numeric@1'] (or iterate if there are
additional numeric ids); replace the single const expand = ... with a forEach
over the id array and run each existing it(...) assertion body against expand =
hooks[id]!.expandNativeType, so every mapped codec ID is validated by the same
test cases.
---
Outside diff comments:
In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Line 144: Replace the unsafe cast "sha256:profile" as never with the proper
constructor call using the imported profileHash function (the same pattern used
in createTestContract); locate the object that sets profileHash and call
profileHash('sha256:profile') to ensure consistent type safety and remove the as
never cast.
---
Nitpick comments:
In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts`:
- Line 11: Remove the inline comment that explains why pgvector was added—since
the change is self-explanatory by adding "pgvector" to extensionPacks, delete
the comment line in the same file so only the code (the extensionPacks array
containing "pgvector") remains; retain the change itself and move any rationale
into the PR/commit message instead.
In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`:
- Around line 10-24: Replace the custom deep-merge in mergePlainObjects with a
well-tested utility: remove or stop using the mergePlainObjects function and
instead import and call a battle-tested deep merge (e.g., lodash.merge or
lodash.mergeWith) wherever mergePlainObjects is used; if bundle size is a
concern, explicitly document the limited behavior of mergePlainObjects and add
unit tests covering edge cases (arrays, non-plain objects, prototypes) and a
TODO to switch to lodash.merge when acceptable. Ensure references to
mergePlainObjects in this module are updated to use the chosen merge function
and keep the same return shape (Record<string, unknown>).
In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Line 78: The file is too large and should be split by the major describe
blocks: extract the "PostgresMigrationPlanner - when database is empty" suite
into a new planner.empty-db.test.ts, move the "composite unique" suite into
planner.unique-constraints.test.ts, and move the "column defaults" suite into
planner.defaults.test.ts; when splitting, preserve each describe(...) block and
its contained tests, update/retain any shared helper imports (e.g.,
setup/teardown helpers, factory functions) at the top of each new file, ensure
exported/used symbols like PostgresMigrationPlanner or helper functions remain
imported from their original modules, and run the test runner to confirm no
missing imports or duplicated globals.
In `@packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts`:
- Around line 5-6: Replace the local redefinitions ExpandFn and HooksMap with
types derived from the source so they track real descriptor shapes: import or
reference typeof
postgresAdapterDescriptorMeta.types.codecTypes.controlPlaneHooks (or the
exported hook/input type) and use that instead of Record<string,...>/manual
function type; update any usages (including the other occurrence around the
block that starts near line 105) to use the derived type so literal keys and
signatures are preserved and tests will catch renames/signature drift.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: e85bc2e0-61a8-4e85-8bf7-c9ed8a747525
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (38)
docs/README.mddocs/glossary.mdexamples/prisma-next-demo/prisma-next.config.tsexamples/prisma-next-demo/src/prisma-no-emit/context.tsexamples/prisma-next-demo/src/queries/get-user-posts.types.test.tsexamples/prisma-next-demo/src/queries/similarity-search.test-d.tsexamples/prisma-next-demo/src/queries/similarity-search.types.test.tspackages/1-framework/1-core/shared/config/src/contract-source-types.tspackages/1-framework/1-core/shared/config/src/exports/config-types.tspackages/1-framework/3-tooling/cli/src/control-api/client.tspackages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.tspackages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.tspackages/1-framework/3-tooling/cli/src/exports/config-types.tspackages/1-framework/3-tooling/cli/src/exports/control-api.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/2-sql/2-authoring/contract-ts/src/config-types.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.tspackages/3-targets/3-targets/postgres/package.jsonpackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.tspackages/3-targets/6-adapters/postgres/test/descriptor-meta.test.tstest/integration/test/authoring/cli.emit-parity-fixtures.test.tstest/integration/test/authoring/parity/core-surface/expected.contract.jsontest/integration/test/authoring/parity/default-cuid-2/expected.contract.jsontest/integration/test/authoring/parity/default-dbgenerated/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid-16/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid/expected.contract.jsontest/integration/test/authoring/parity/default-ulid/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v4/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v7/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/expected.contract.jsontest/integration/test/authoring/parity/relation-backrelation-list/expected.contract.jsontest/integration/test/authoring/psl.pgvector-dbinit.test.tstest/integration/test/authoring/templates/prisma-next.config.parity-psl.tstest/integration/test/cli.emit-command.test.ts
💤 Files with no reviewable changes (1)
- test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
✅ Files skipped from review due to trivial changes (1)
- docs/glossary.md
🚧 Files skipped from review as they are similar to previous changes (2)
- examples/prisma-next-demo/prisma-next.config.ts
- examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
9f2b805 to
00d4764
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/integration/test/cli.emit-contract.test.ts (1)
11-19:⚠️ Potential issue | 🟡 MinorDon’t bake an empty
ContractSourceContextinto the helper.This helper now resolves every contract source as if no extension packs were composed. That means this integration suite will miss regressions in context-aware sources and can diverge from the real emit path as soon as a fixture depends on
composedExtensionPacks. Please thread the actual context in from the loaded config instead of hardcoding[].🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/cli.emit-contract.test.ts` around lines 11 - 19, The helper resolveContractIR currently calls the contract source with a hardcoded composedExtensionPacks: [] which hides regressions for context-aware sources; update resolveContractIR to accept or obtain the real ContractSourceContext from the loaded config and pass its composedExtensionPacks through to source instead of an empty array (e.g., thread the context returned by loadConfig into resolveContractIR and call source({ composedExtensionPacks: actualContext.composedExtensionPacks }) so the helper mirrors the real emit path).
♻️ Duplicate comments (1)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (1)
1028-1040:⚠️ Potential issue | 🟡 MinorReject
@relation(map: ...)on backrelation-list fields.Parsing
maphere makes it valid on every relation attribute, but the list-side backrelation branch later only rejectsfields/referencesand referential actions.@relation(map: ...)on the navigation-list side is therefore accepted and silently dropped, so users can think they've named the FK when the emitted contract still uses the default.💡 Proposed fix
if (parsedRelation.onDelete || parsedRelation.onUpdate) { diagnostics.push({ code: 'PSL_INVALID_RELATION_ATTRIBUTE', message: `Backrelation list field "${model.name}.${field.name}" cannot declare onDelete/onUpdate; define referential actions on the FK-side relation field`, sourceId, span: relationAttribute.span, }); continue; } + if (parsedRelation.constraintName) { + diagnostics.push({ + code: 'PSL_INVALID_RELATION_ATTRIBUTE', + message: `Backrelation list field "${model.name}.${field.name}" cannot declare map; define FK constraint names on the FK-side relation field`, + sourceId, + span: relationAttribute.span, + }); + continue; + } relationName = parsedRelation.relationName;Also applies to: 1080-1085
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 1028 - 1040, The parser currently accepts a `@relation`(map: "...") on the navigation-list (backrelation) side because it only validates quoted-string syntax; change the logic that reads constraintNameRaw/constraintName to reject the presence of a map argument when the relation attribute is the list/backrelation side: detect the backrelation-list case using the existing input metadata (the same flags used later to reject fields/references and referential actions) and if constraintNameRaw is present push a diagnostic (code 'PSL_INVALID_RELATION_ATTRIBUTE', message indicating map is not allowed on the backrelation-list for input.modelName.input.fieldName, include sourceId and attribute.span) and return undefined; apply the same rejection at the other symmetric spot mentioned (around the later 1080-1085 block) so both places consistently disallow `@relation`(map: ...) on list/backrelation fields.
🧹 Nitpick comments (6)
examples/prisma-next-demo/src/prisma-no-emit/context.ts (1)
11-11: Consider removing the explanatory comment.The comment provides historical context, but per coding guidelines, comments should be avoided when code can express intent. The addition of
pgvectortoextensionPacksis self-explanatory alongside the import.🧹 Proposed removal
-// pgvector was previously missing here; added for parity with the emit workflow config. export const stack = createSqlExecutionStack({🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts` at line 11, Remove the historical/explanatory comment that reads about "pgvector was previously missing here; added for parity with the emit workflow config." and leave the import and the addition to extensionPacks as-is; locate the comment near the pgvector import and the extensionPacks array in this file (reference symbols: pgvector, extensionPacks) and delete that single-line comment so the code itself expresses the intent.packages/3-extensions/pgvector/src/exports/control.ts (1)
74-82: Preserve existingcontrolPlaneHooksentries when extendingcodecTypes.This currently replaces
codecTypes.controlPlaneHooksoutright. IfpgvectorPackMeta.types.codecTypesever carries another hook, it gets dropped here. Merge the existing map before addingPGVECTOR_CODEC_ID.♻️ Proposed change
types: { ...pgvectorPackMeta.types, codecTypes: { ...pgvectorPackMeta.types.codecTypes, controlPlaneHooks: { + ...(pgvectorPackMeta.types.codecTypes.controlPlaneHooks ?? {}), [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks, }, }, },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/pgvector/src/exports/control.ts` around lines 74 - 82, The current assignment of codecTypes.controlPlaneHooks overwrites any existing entries; update the merge to preserve existing hooks by spreading the existing map before adding our entry — when building types use pgvectorPackMeta.types.codecTypes.controlPlaneHooks (if present) and spread it, then add [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so other controlPlaneHooks are retained.packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts (2)
22-45: Make the descriptor mocks explicit test-only escapes.Both helpers end with direct casts to
TargetBoundComponentDescriptor<...>. In test code we standardize on keeping the unsafe boundary explicit withas unknown as ...at the mock return site, rather than a direct cast that hides how partial the fixture is.As per coding guidelines, "Use double casts (
as unknown as X) for mocks and dynamic proxies in tests instead of direct casts" and "Place type casts at mock boundaries (return statements), not sprinkled throughout the test."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts` around lines 22 - 45, The two test helper functions makeAdapter and makeExtension currently use direct casts to TargetBoundComponentDescriptor<'sql','postgres'> which hides the partial nature of the fixtures; update their return assertions to use the explicit test-only escape pattern by changing the cast to "as unknown as TargetBoundComponentDescriptor<'sql','postgres'>" at the return site so the unsafe boundary is explicit for these mocks.
6-20: Use the sharedcreateContractIR()fixture instead of hand-building IR objects.
makeIR()duplicates the base ContractIR shape in a new test file, which makes this suite more brittle as the IR evolves. Please switch this helper to the shared factory so defaults and required fields stay centralized.As per coding guidelines, "Use factory functions like
createContractIR()instead of manual object creation for ContractIR objects in tests to avoid duplication, ensure all required fields are present with proper defaults, and simplify refactoring."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts` around lines 6 - 20, The test defines a local makeIR() that hand-builds a ContractIR; replace it by importing and using the shared factory createContractIR() (and remove the local makeIR) so the test uses centralized defaults and required fields; update any calls that passed overrides to call createContractIR(overrides) (or createContractIR({...}) as needed) and add the appropriate import for createContractIR at the top of the file, referencing the existing ContractIR type only if needed for typing.packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts (1)
231-283: Split this test file before adding more planner scenarios.This file is already well past the 500-line limit and now mixes additive planning, parameterized/native-type rendering, composite-unique DDL, and default rendering in one place. Please move the new parameterized-type cases into a focused file such as
planner.parameterized-types.test.tsso the suite stays navigable.As per coding guidelines, "Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files." and "Split test files when they exceed 500 lines, contain multiple distinct concerns that can be logically separated, or have multiple top-level
describeblocks that can be split by functionality."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts` around lines 231 - 283, The test file has grown too large and mixes multiple planner concerns; extract parameterized/native-type rendering tests (e.g., the "renders pgvector vector(N) column types in DDL" it-block that uses createPostgresMigrationPlanner, planner.plan, and pgvectorDescriptor) into a new focused test file (suggested name: planner.parameterized-types.test.ts). Move only the parameterized-type cases and their fixtures (contract objects, emptySchema, INIT_ADDITIVE_POLICY, and any descriptors like pgvectorDescriptor) into the new file, keep imports/setup the same, and remove those tests from the original file so each file stays under 500 lines and focuses on a single concern.packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts (1)
41-43: NarrowsortDeepTyped()to the shapes it actually preserves.
sortDeep()rebuilds arrays and plain objects, soas Toverpromises that the original static type survives unchanged. I’d constrain this helper to the record-like IR shapes it actually handles, or narrow at the call sites instead of hiding the conversion behind a generic cast.As per coding guidelines, “Replace blind casts with type predicates instead of
ascasts.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts` around lines 41 - 43, The helper sortDeepTyped currently lies about preserving arbitrary T by casting sortDeep(value) as T; change its signature and usages to reflect the actual shapes handled (plain objects and arrays) — e.g., restrict the parameter to Record<string, unknown> | unknown[] (or create explicit overloads) and return the same narrowed type instead of using a blind generic cast; alternatively implement a type predicate (isPlainObjectOrArray) and narrow at call sites before calling sortDeepTyped so you no longer need the unsafe `as T` cast.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`:
- Around line 90-93: The code currently sets base['types'] to a clone that only
removes controlPlaneHooks at the codecTypes object level, but you need to remove
controlPlaneHooks from each codec descriptor inside types.codecTypes so hook
functions don't propagate; update the logic where base['types'] is assigned (the
branch that checks types.codecTypes) to iterate over types.codecTypes entries
(or map its values) and for each codec descriptor produce a shallow clone with
controlPlaneHooks omitted, then assign the new codecTypes map into the cloned
types object before putting it on base; reference symbols: base, types,
codecTypes, controlPlaneHooks.
In `@packages/2-sql/2-authoring/contract-psl/test/provider.test.ts`:
- Around line 257-268: The test's assertion uses optional chaining
storage.tables['document']?.columns['embedding'] which will silently pass if the
embedding column is missing; change the check to access the column directly
(storage.tables['document'].columns['embedding']) so it will throw if the column
is absent, and ensure you assert the column exists before testing properties
(use the already-validated shape from the previous expect on storage.tables to
justify direct access). This targets the storage.tables -> 'document' -> columns
-> 'embedding' path and removes the optional chaining to make the typeRef
assertion meaningful and fail when embedding is missing.
In `@packages/3-targets/3-targets/postgres/src/exports/control.ts`:
- Around line 18-34: The buildNativeTypeExpander currently silently falls back
to input.nativeType which loses parameter information; update
buildNativeTypeExpander (and the similar code at the other occurrence) so that
it still returns a callable expander but it fails fast when typeParams are
present and cannot be expanded: keep returning input.nativeType only when there
are no typeParams; if input.typeParams exists and frameworkComponents is
missing, codecId is missing, or there is no expandNativeType hook on
codecHooks.get(codecId), throw a descriptive Error indicating that native type
expansion failed for the given codecId and typeParams (include codecId and
typeParams in the message) so callers like contractToSchema cannot synthesize
lossy types silently.
In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 87-115: The function expandNumeric currently allows a lone "scale"
param to be ignored; update expandNumeric to treat a present scale without
precision as an error: inside expandNumeric (function name: expandNumeric,
symbols: nativeType, typeParams, hasPrecision, hasScale) if hasScale is true and
hasPrecision is false throw a descriptive Error (e.g., "Invalid type parameters
for \"numeric\": scale provided without precision") rather than returning
nativeType; keep existing numeric validation logic for precision/scale when both
are present.
In `@test/integration/test/authoring/cli.emit-parity-fixtures.test.ts`:
- Around line 115-124: The PSL path is currently built using the TS fixture's
framework stack (tsConfig -> frameworkComponents) and validated with the TS
family, which can mask drift; change the PSL branch to construct its own
frameworkComponents from the PSL fixture (use pslConfig.target,
pslConfig.adapter, pslConfig.extensionPacks) and pass that into enrichContractIR
when creating enrichedPsl, and then validate normalizedPsl with the PSL family
instance (pslFamilyInstance.validateContractIR) instead of
familyInstance.validateContractIR so the PSL capabilities/extensionPacks are
accurately tested.
---
Outside diff comments:
In `@test/integration/test/cli.emit-contract.test.ts`:
- Around line 11-19: The helper resolveContractIR currently calls the contract
source with a hardcoded composedExtensionPacks: [] which hides regressions for
context-aware sources; update resolveContractIR to accept or obtain the real
ContractSourceContext from the loaded config and pass its composedExtensionPacks
through to source instead of an empty array (e.g., thread the context returned
by loadConfig into resolveContractIR and call source({ composedExtensionPacks:
actualContext.composedExtensionPacks }) so the helper mirrors the real emit
path).
---
Duplicate comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 1028-1040: The parser currently accepts a `@relation`(map: "...") on
the navigation-list (backrelation) side because it only validates quoted-string
syntax; change the logic that reads constraintNameRaw/constraintName to reject
the presence of a map argument when the relation attribute is the
list/backrelation side: detect the backrelation-list case using the existing
input metadata (the same flags used later to reject fields/references and
referential actions) and if constraintNameRaw is present push a diagnostic (code
'PSL_INVALID_RELATION_ATTRIBUTE', message indicating map is not allowed on the
backrelation-list for input.modelName.input.fieldName, include sourceId and
attribute.span) and return undefined; apply the same rejection at the other
symmetric spot mentioned (around the later 1080-1085 block) so both places
consistently disallow `@relation`(map: ...) on list/backrelation fields.
---
Nitpick comments:
In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts`:
- Line 11: Remove the historical/explanatory comment that reads about "pgvector
was previously missing here; added for parity with the emit workflow config."
and leave the import and the addition to extensionPacks as-is; locate the
comment near the pgvector import and the extensionPacks array in this file
(reference symbols: pgvector, extensionPacks) and delete that single-line
comment so the code itself expresses the intent.
In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`:
- Around line 41-43: The helper sortDeepTyped currently lies about preserving
arbitrary T by casting sortDeep(value) as T; change its signature and usages to
reflect the actual shapes handled (plain objects and arrays) — e.g., restrict
the parameter to Record<string, unknown> | unknown[] (or create explicit
overloads) and return the same narrowed type instead of using a blind generic
cast; alternatively implement a type predicate (isPlainObjectOrArray) and narrow
at call sites before calling sortDeepTyped so you no longer need the unsafe `as
T` cast.
In
`@packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts`:
- Around line 22-45: The two test helper functions makeAdapter and makeExtension
currently use direct casts to TargetBoundComponentDescriptor<'sql','postgres'>
which hides the partial nature of the fixtures; update their return assertions
to use the explicit test-only escape pattern by changing the cast to "as unknown
as TargetBoundComponentDescriptor<'sql','postgres'>" at the return site so the
unsafe boundary is explicit for these mocks.
- Around line 6-20: The test defines a local makeIR() that hand-builds a
ContractIR; replace it by importing and using the shared factory
createContractIR() (and remove the local makeIR) so the test uses centralized
defaults and required fields; update any calls that passed overrides to call
createContractIR(overrides) (or createContractIR({...}) as needed) and add the
appropriate import for createContractIR at the top of the file, referencing the
existing ContractIR type only if needed for typing.
In `@packages/3-extensions/pgvector/src/exports/control.ts`:
- Around line 74-82: The current assignment of codecTypes.controlPlaneHooks
overwrites any existing entries; update the merge to preserve existing hooks by
spreading the existing map before adding our entry — when building types use
pgvectorPackMeta.types.codecTypes.controlPlaneHooks (if present) and spread it,
then add [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so other controlPlaneHooks
are retained.
In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Around line 231-283: The test file has grown too large and mixes multiple
planner concerns; extract parameterized/native-type rendering tests (e.g., the
"renders pgvector vector(N) column types in DDL" it-block that uses
createPostgresMigrationPlanner, planner.plan, and pgvectorDescriptor) into a new
focused test file (suggested name: planner.parameterized-types.test.ts). Move
only the parameterized-type cases and their fixtures (contract objects,
emptySchema, INIT_ADDITIVE_POLICY, and any descriptors like pgvectorDescriptor)
into the new file, keep imports/setup the same, and remove those tests from the
original file so each file stays under 500 lines and focuses on a single
concern.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 3e24f6c0-50a8-43fd-bb90-fa4e45e8ad70
⛔ Files ignored due to path filters (6)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.mdis excluded by!projects/**projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/code-review.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/system-design-review.mdis excluded by!projects/**projects/psl-contract-authoring/specs/reviews/walkthrough.mdis excluded by!projects/**
📒 Files selected for processing (68)
docs/README.mddocs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.mddocs/glossary.mdexamples/prisma-next-demo/README.mdexamples/prisma-next-demo/package.jsonexamples/prisma-next-demo/prisma-next.config.tsexamples/prisma-next-demo/prisma-next.config.ts-contract.tsexamples/prisma-next-demo/prisma/schema.prismaexamples/prisma-next-demo/src/prisma-no-emit/context.tsexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/src/queries/get-user-posts.types.test.tsexamples/prisma-next-demo/src/queries/similarity-search.test-d.tsexamples/prisma-next-demo/src/queries/similarity-search.tsexamples/prisma-next-demo/src/queries/similarity-search.types.test.tsexamples/prisma-next-demo/test/utils/control-client.tspackages/1-framework/1-core/migration/control-plane/src/migrations.tspackages/1-framework/1-core/shared/config/src/contract-source-types.tspackages/1-framework/1-core/shared/config/src/exports/config-types.tspackages/1-framework/3-tooling/cli/src/commands/migration-plan.tspackages/1-framework/3-tooling/cli/src/control-api/client.tspackages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.tspackages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.tspackages/1-framework/3-tooling/cli/src/exports/config-types.tspackages/1-framework/3-tooling/cli/src/exports/control-api.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/2-sql/2-authoring/contract-ts/src/config-types.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.tspackages/3-extensions/pgvector/src/exports/column-types.tspackages/3-extensions/pgvector/src/exports/control.tspackages/3-extensions/pgvector/test/column-types.test.tspackages/3-targets/3-targets/postgres/package.jsonpackages/3-targets/3-targets/postgres/src/core/migrations/planner-reconciliation.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.tspackages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-targets/3-targets/postgres/test/migrations/planner.reconciliation-unit.test.tspackages/3-targets/6-adapters/postgres/src/core/descriptor-meta.tspackages/3-targets/6-adapters/postgres/src/core/parameterized-types.tspackages/3-targets/6-adapters/postgres/src/exports/control.tspackages/3-targets/6-adapters/postgres/test/descriptor-meta.test.tspackages/3-targets/6-adapters/postgres/test/parameterized-types.test.tstest/integration/test/authoring/cli.emit-parity-fixtures.test.tstest/integration/test/authoring/parity/core-surface/expected.contract.jsontest/integration/test/authoring/parity/default-cuid-2/expected.contract.jsontest/integration/test/authoring/parity/default-dbgenerated/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid-16/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid/expected.contract.jsontest/integration/test/authoring/parity/default-ulid/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v4/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v7/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/contract.tstest/integration/test/authoring/parity/map-attributes/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/schema.prismatest/integration/test/authoring/parity/pgvector-named-type/contract.tstest/integration/test/authoring/parity/pgvector-named-type/expected.contract.jsontest/integration/test/authoring/parity/relation-backrelation-list/expected.contract.jsontest/integration/test/authoring/psl.pgvector-dbinit.test.tstest/integration/test/authoring/templates/prisma-next.config.parity-psl.tstest/integration/test/cli.emit-command.test.tstest/integration/test/cli.emit-contract.test.ts
💤 Files with no reviewable changes (3)
- packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
- test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
- packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
✅ Files skipped from review due to trivial changes (1)
- examples/prisma-next-demo/README.md
🚧 Files skipped from review as they are similar to previous changes (20)
- packages/3-targets/3-targets/postgres/package.json
- test/integration/test/authoring/parity/core-surface/expected.contract.json
- examples/prisma-next-demo/prisma-next.config.ts
- examples/prisma-next-demo/prisma-next.config.ts-contract.ts
- examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
- test/integration/test/authoring/parity/map-attributes/contract.ts
- test/integration/test/cli.emit-command.test.ts
- packages/1-framework/3-tooling/cli/test/config-types.test.ts
- examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
- packages/3-extensions/pgvector/src/exports/column-types.ts
- packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
- packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
- test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
- packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
- packages/3-extensions/pgvector/test/column-types.test.ts
- packages/1-framework/3-tooling/cli/src/exports/config-types.ts
- docs/glossary.md
- packages/1-framework/3-tooling/cli/src/control-api/client.ts
- examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
- test/integration/test/authoring/parity/pgvector-named-type/contract.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts (1)
93-127: Unreachable fallback at line 126.The
return nativeTypeat line 126 is unreachable: if we reach line 107,hasPrecisionis guaranteedtrue(due to the early return at lines 97-99 and the throw at lines 101-105), so the function always returns from within theif (hasPrecision)block.This doesn't affect correctness but could be simplified.
♻️ Suggested simplification
if (hasPrecision) { const precision = typeParams['precision']; if (!isPositiveInteger(precision)) { throw new Error( `Invalid "precision" type parameter for "${nativeType}": expected a positive integer, got ${JSON.stringify(precision)}`, ); } if (hasScale) { const scale = typeParams['scale']; if (!isNonNegativeInteger(scale)) { throw new Error( `Invalid "scale" type parameter for "${nativeType}": expected a non-negative integer, got ${JSON.stringify(scale)}`, ); } return `${nativeType}(${precision},${scale})`; } return `${nativeType}(${precision})`; } - - return nativeType; + // Unreachable: hasPrecision is guaranteed true here due to early returns above }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts` around lines 93 - 127, The final fallback return in expandNumeric is unreachable; simplify the function by removing the redundant "return nativeType" at the end and adjust control flow so all code paths return inside the existing checks (keep the initial early return when both hasPrecision and hasScale are false, the throw when scale is present without precision, and the returns inside the if (hasPrecision) block). This targets the expandNumeric function and ensures no dead code remains while preserving existing validation and error messages.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 93-127: The final fallback return in expandNumeric is unreachable;
simplify the function by removing the redundant "return nativeType" at the end
and adjust control flow so all code paths return inside the existing checks
(keep the initial early return when both hasPrecision and hasScale are false,
the throw when scale is present without precision, and the returns inside the if
(hasPrecision) block). This targets the expandNumeric function and ensures no
dead code remains while preserving existing validation and error messages.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 65bc8193-38da-47c8-8f7e-28426b2a34cc
📒 Files selected for processing (8)
examples/prisma-next-demo/src/queries/get-user-posts.types.test.tsexamples/prisma-next-demo/src/queries/similarity-search.test-d.tsexamples/prisma-next-demo/src/queries/similarity-search.types.test.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/6-adapters/postgres/src/core/descriptor-meta.tspackages/3-targets/6-adapters/postgres/test/descriptor-meta.test.tstest/utils/src/typed-expectations.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
- packages/3-targets/3-targets/postgres/src/exports/control.ts
Add failing coverage for framework metadata emission, pgvector vector(N) type expansion, and Prisma-style relation map FK naming so we can implement fixes with confidence.
Allow PSL contract source to carry configured extension pack metadata and a merged capability matrix, so emitted contracts are complete without app-level enrichment.
Teach the Postgres parameterized type expander to render vector(length) for pgvector columns, so migration DDL uses valid parameterized types without quoting.
Represent pgvector columns and aliases as nativeType "vector" with typeParams.length, so planners can safely expand to vector(N) without quoting or unsafe nativeType strings.
Accept Prisma-style relation map arguments on FK-side relations and propagate the constraint name into contract storage so migrations can create stable FK names.
Make vector(N) descriptors use nativeType "vector" plus typeParams.length so Postgres DDL expansion can render vector(N) without tripping native type safety checks.
Align TS/PSL parity fixtures with pgvector parameterized native type normalization, provider-emitted framework metadata, and @relation(map: ...) FK constraint naming.
Switch the demo emit workflow to use prismaContract(schema.prisma) and rely on core provider metadata/vector handling, then re-emit contract artifacts and adjust type tests.
Remove the options cast so the provider test exercises the real prismaContract API surface for extensionPacks and capabilitySources.
Make capabilitySources a typed interface and merge/sort metadata without casting the interpreted ContractIR, keeping provider enrichment type-safe and self-documenting.
Add a PSL→emit→dbInit integration test for dimensioned pgvector columns, and teach pgvector control-plane hooks to expand vector(N) so schema verification matches DDL.
…scriptor Move vector(N) native type expansion hooks onto the control extension descriptor so schema verification can expand expected types without embedding functions in pack metadata.
…xtension pack metadata
…builder terminology
…sts to table-driven
…nd missing expander hooks
60c868e to
05f27ff
Compare
There was a problem hiding this comment.
Actionable comments posted: 7
♻️ Duplicate comments (1)
packages/3-targets/3-targets/postgres/src/exports/control.ts (1)
18-24:⚠️ Potential issue | 🟠 MajorDon't drop the expander when
frameworkComponentsis missing.Returning
undefinedhere reopens the lossy path for parameterized contracts:contractToSchema()passes noexpandNativeType, so callers that omitframeworkComponentscan still collapsecharacter(36)/vector(1536)to the bare native type instead of failing fast. Keep returning an expander and make the "no components" case throw whenevertypeParamsare present. As per coding guidelines, "Do not treat missing type parameters as a successful match when the contract declares them."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/postgres/src/exports/control.ts` around lines 18 - 24, The current buildNativeTypeExpander returns undefined when frameworkComponents is missing which allows lossy matches; change buildNativeTypeExpander to always return an expander function (rather than undefined) and, when frameworkComponents is absent, have that expander throw if the provided native type descriptor includes typeParams; locate buildNativeTypeExpander and its use of extractCodecControlHooks and modify the returned closure so it validates typeParams and raises an error for any parameterized native type, while still delegating to extractCodecControlHooks when frameworkComponents are present.
🧹 Nitpick comments (4)
examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts (1)
15-16: Consider extractingNotNeverto shared utilities.This helper type is useful for verifying a type resolved to something other than
never. If this pattern is needed elsewhere, consider adding it to@prisma-next/test-utils/typed-expectationsalongsideEqualandExpect.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts` around lines 15 - 16, The type alias NotNever<T> used in get-user-posts.types.test.ts should be moved into the shared test utilities so it can be reused; create (or add) NotNever in the `@prisma-next/test-utils/typed-expectations` module alongside Equal and Expect, export it, then replace the local declaration in get-user-posts.types.test.ts with an import of NotNever from that module (keep the exact type name NotNever to match usages).packages/2-sql/2-authoring/contract-psl/src/provider.ts (1)
52-56: Consider simplifying the result handling.The explicit check and re-wrap could be simplified since
interpretedis already aResult. However, this pattern is acceptable if there's a need for additional processing or type narrowing in the future.// Current (explicit) if (!interpreted.ok) { return interpreted; } return ok(interpreted.value); // Simplified alternative return interpreted;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts` around lines 52 - 56, The code in provider.ts performs an unnecessary explicit check and re-wrap for the Result held in the local variable `interpreted`; replace the if-block that checks `if (!interpreted.ok) { return interpreted; } return ok(interpreted.value);` with a single `return interpreted;` (leave that simplification in the function/method where `interpreted` is produced) unless you intend to add extra processing or type narrowing later.test/integration/test/cli.emit-contract.test.ts (1)
2-2: Consider usingpatheinstead ofnode:path.Based on learnings, prefer
patheovernode:pathfor path operations in TypeScript files for consistent cross-platform behavior.Suggested import change
-import { dirname, join, resolve } from 'node:path'; +import { dirname, join, resolve } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/cli.emit-contract.test.ts` at line 2, Replace the import from 'node:path' with equivalent imports from 'pathe' and update usages accordingly: import dirname, join, resolve from 'pathe' instead of 'node:path' so functions dirname, join, and resolve in the test (e.g., in cli.emit-contract.test.ts) use pathe's cross-platform implementations; ensure any existing calls using these symbols continue to work without further changes.test/integration/test/cli.emit-command.test.ts (1)
2-2: Consider usingpatheinstead ofnode:path.Based on learnings, prefer
patheovernode:pathfor path operations in TypeScript files for consistent cross-platform behavior.Suggested import change
-import { join } from 'node:path'; +import { join } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/cli.emit-command.test.ts` at line 2, The import in cli.emit-command.test.ts currently pulls join from 'node:path'; change it to import join from 'pathe' (or import { join } from 'pathe' to match usage) to ensure consistent cross-platform path handling; update any other path utility imports in this file (e.g., uses of join) to rely on the pathe import and run the tests to verify no type or runtime changes are needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md:
- Around line 27-33: Update the ADR to document the enforced validation/error
semantics: state that CodecControlHooks.expandNativeType must be provided for
any codec that exposes parameterized native types, that missing expandNativeType
support is a hard error (no fallback to stringly rendering), and that invalid
parameter sets returned/encountered during expansion are rejected with an error;
mention where this enforcement applies (DDL/migrations migration planner, schema
verifier’s expected-type expansion, and contractToSchema/NativeTypeExpander
offline planning) and add the same text to the implementation notes and decision
sections (also apply the update to the corresponding paragraphs around lines
45-48).
- Around line 39-40: Update the overgeneralized sentence about adapter coupling
to clarify that "no adapter changes needed" applies only to extension-owned
parameterized native types that implement an expandNativeType hook on their
controlPlaneHooks; state that adapter-owned built-in native types still require
adapter hook changes. Specifically, revise the two bullet points referencing
expandNativeType and controlPlaneHooks to narrowly qualify the decoupling
guarantee and mention adapter-owned native types as an exception so the ADR no
longer overstates the claim.
In `@docs/glossary.md`:
- Around line 3-5: The glossary currently mixes stable public names with planned
renames (e.g., prismaSchema(), typescriptSchema(), schema:) which confuses
consumers; update docs/glossary.md by splitting content into two clear sections
— "Current public terms" containing only the terminology safe to use today, and
"Planned/Refactor terminology" containing the tracker entries like
prismaSchema(), typescriptSchema(), and schema:, or alternatively move the
entire tracker block into a separate architecture/refactor document; ensure each
section is labeled and add a brief note indicating the stability status next to
any planned term.
- Around line 89-92: Update the "Capability" glossary entry to describe
capability matching as an adapter-reported, connect-time negotiation rather than
a startup check: rephrase the sentence that currently says "Prisma Next checks
these match at startup" to indicate that the adapter reports provided
capabilities at connect time and Prisma Next negotiates/validates the contract's
required capabilities against those provided by the adapter when establishing
the connection; ensure the wording frames the contract's capabilities as
requirements the contract declares and the adapter's capabilities as what it
provides.
In `@examples/prisma-next-demo/prisma-next.config.ts`:
- Around line 16-18: The relative schema path passed to prismaContract is
resolved from the process CWD, so change the call to compute an absolute path
anchored to this config file (e.g. require('path').resolve(__dirname,
'./prisma/schema.prisma')) and pass that resolved path into prismaContract
(update the prismaContract(...) invocation). This ensures prismaContract
receives an absolute schemaPath regardless of where the process is started.
In
`@packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts`:
- Around line 25-30: The test helper expandParameterizedNativeType currently
returns input.nativeType when codecId is missing or hook lookup fails, masking
parameterized-type failures; update it to mirror production fail-fast semantics
used in control.ts by (1) rejecting/throwing when input.codecId is falsy, (2)
throwing if adapterCodecHooks.get(input.codecId) is undefined or if
hooks.expandNativeType is undefined, and only calling
hooks.expandNativeType(input) when present; reference the functions/values
expandParameterizedNativeType, extractCodecControlHooks, and adapterCodecHooks
(or alternatively route the test to use the public adapter descriptor path) so
missing type parameters cause test failures instead of silently returning
input.nativeType.
In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 80-90: expandPrecision currently rejects precision 0 by using
isPositiveInteger; change validation to allow zero for PostgreSQL temporal
types. In the expandPrecision function (signature ExpandNativeTypeInput) detect
temporal native types ("timestamp", "timestamptz", "time", "timetz", "interval")
and validate precision with a non-negative integer check (allow 0) for those
types, while keeping the existing isPositiveInteger validation for other native
types; ensure the error message still includes the invalid value via
JSON.stringify. Also update the corresponding tests in
packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts to cover
precision 0 for the temporal codecs and maintain existing numeric tests.
---
Duplicate comments:
In `@packages/3-targets/3-targets/postgres/src/exports/control.ts`:
- Around line 18-24: The current buildNativeTypeExpander returns undefined when
frameworkComponents is missing which allows lossy matches; change
buildNativeTypeExpander to always return an expander function (rather than
undefined) and, when frameworkComponents is absent, have that expander throw if
the provided native type descriptor includes typeParams; locate
buildNativeTypeExpander and its use of extractCodecControlHooks and modify the
returned closure so it validates typeParams and raises an error for any
parameterized native type, while still delegating to extractCodecControlHooks
when frameworkComponents are present.
---
Nitpick comments:
In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts`:
- Around line 15-16: The type alias NotNever<T> used in
get-user-posts.types.test.ts should be moved into the shared test utilities so
it can be reused; create (or add) NotNever in the
`@prisma-next/test-utils/typed-expectations` module alongside Equal and Expect,
export it, then replace the local declaration in get-user-posts.types.test.ts
with an import of NotNever from that module (keep the exact type name NotNever
to match usages).
In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts`:
- Around line 52-56: The code in provider.ts performs an unnecessary explicit
check and re-wrap for the Result held in the local variable `interpreted`;
replace the if-block that checks `if (!interpreted.ok) { return interpreted; }
return ok(interpreted.value);` with a single `return interpreted;` (leave that
simplification in the function/method where `interpreted` is produced) unless
you intend to add extra processing or type narrowing later.
In `@test/integration/test/cli.emit-command.test.ts`:
- Line 2: The import in cli.emit-command.test.ts currently pulls join from
'node:path'; change it to import join from 'pathe' (or import { join } from
'pathe' to match usage) to ensure consistent cross-platform path handling;
update any other path utility imports in this file (e.g., uses of join) to rely
on the pathe import and run the tests to verify no type or runtime changes are
needed.
In `@test/integration/test/cli.emit-contract.test.ts`:
- Line 2: Replace the import from 'node:path' with equivalent imports from
'pathe' and update usages accordingly: import dirname, join, resolve from
'pathe' instead of 'node:path' so functions dirname, join, and resolve in the
test (e.g., in cli.emit-contract.test.ts) use pathe's cross-platform
implementations; ensure any existing calls using these symbols continue to work
without further changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: c644e868-0bf9-4a88-83b7-4f5d83d74683
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.mdis excluded by!projects/**projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.mdis excluded by!projects/**
📒 Files selected for processing (68)
.gitignoredocs/README.mddocs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.mddocs/glossary.mdexamples/prisma-next-demo/README.mdexamples/prisma-next-demo/package.jsonexamples/prisma-next-demo/prisma-next.config.tsexamples/prisma-next-demo/prisma-next.config.ts-contract.tsexamples/prisma-next-demo/prisma/schema.prismaexamples/prisma-next-demo/src/prisma-no-emit/context.tsexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/src/queries/get-user-posts.types.test.tsexamples/prisma-next-demo/src/queries/similarity-search.test-d.tsexamples/prisma-next-demo/src/queries/similarity-search.tsexamples/prisma-next-demo/src/queries/similarity-search.types.test.tsexamples/prisma-next-demo/test/utils/control-client.tspackages/1-framework/1-core/shared/config/src/contract-source-types.tspackages/1-framework/1-core/shared/config/src/exports/config-types.tspackages/1-framework/3-tooling/cli/src/control-api/client.tspackages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.tspackages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.tspackages/1-framework/3-tooling/cli/src/exports/config-types.tspackages/1-framework/3-tooling/cli/src/exports/control-api.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/2-sql/2-authoring/contract-ts/src/config-types.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.tspackages/3-extensions/pgvector/src/exports/column-types.tspackages/3-extensions/pgvector/src/exports/control.tspackages/3-extensions/pgvector/test/column-types.test.tspackages/3-targets/3-targets/postgres/package.jsonpackages/3-targets/3-targets/postgres/src/core/migrations/planner-reconciliation.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.tspackages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-targets/3-targets/postgres/test/migrations/planner.reconciliation-unit.test.tspackages/3-targets/6-adapters/postgres/src/core/descriptor-meta.tspackages/3-targets/6-adapters/postgres/src/core/parameterized-types.tspackages/3-targets/6-adapters/postgres/src/exports/control.tspackages/3-targets/6-adapters/postgres/test/descriptor-meta.test.tspackages/3-targets/6-adapters/postgres/test/parameterized-types.test.tstest/integration/test/authoring/cli.emit-parity-fixtures.test.tstest/integration/test/authoring/parity/core-surface/expected.contract.jsontest/integration/test/authoring/parity/default-cuid-2/expected.contract.jsontest/integration/test/authoring/parity/default-dbgenerated/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid-16/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid/expected.contract.jsontest/integration/test/authoring/parity/default-ulid/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v4/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v7/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/contract.tstest/integration/test/authoring/parity/map-attributes/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/schema.prismatest/integration/test/authoring/parity/pgvector-named-type/contract.tstest/integration/test/authoring/parity/pgvector-named-type/expected.contract.jsontest/integration/test/authoring/parity/relation-backrelation-list/expected.contract.jsontest/integration/test/authoring/psl.pgvector-dbinit.test.tstest/integration/test/authoring/templates/prisma-next.config.parity-psl.tstest/integration/test/cli.emit-command.test.tstest/integration/test/cli.emit-contract.test.tstest/utils/src/typed-expectations.ts
💤 Files with no reviewable changes (3)
- packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
- test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
- packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
🚧 Files skipped from review as they are similar to previous changes (26)
- packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
- packages/1-framework/3-tooling/cli/src/control-api/client.ts
- test/integration/test/authoring/parity/default-ulid/expected.contract.json
- test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
- packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
- examples/prisma-next-demo/README.md
- packages/3-targets/3-targets/postgres/package.json
- test/integration/test/authoring/psl.pgvector-dbinit.test.ts
- packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
- examples/prisma-next-demo/package.json
- packages/1-framework/3-tooling/cli/src/exports/control-api.ts
- test/integration/test/authoring/parity/map-attributes/contract.ts
- packages/3-extensions/pgvector/src/exports/control.ts
- test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
- packages/2-sql/2-authoring/contract-ts/src/config-types.ts
- test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
- packages/3-targets/6-adapters/postgres/src/exports/control.ts
- packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts
- packages/3-targets/3-targets/postgres/test/migrations/planner.reconciliation-unit.test.ts
- packages/3-extensions/pgvector/test/column-types.test.ts
- packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
- examples/prisma-next-demo/src/prisma-no-emit/context.ts
- examples/prisma-next-demo/test/utils/control-client.ts
- test/integration/test/authoring/parity/default-nanoid-16/expected.contract.json
- test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
- test/integration/test/authoring/cli.emit-parity-fixtures.test.ts
| Expansion to a parameterized SQL type string (for example `vector(1536)`) is the responsibility of each component (adapter or extension) that owns the codec, via `CodecControlHooks.expandNativeType`: | ||
|
|
||
| - DDL/migrations: the migration planner extracts codec hooks from framework components and uses them when rendering column types. | ||
| - Schema verification: the schema verifier uses the same hooks to expand the *expected* type before comparing to introspected schema types. | ||
| - `contractToSchema`: receives framework components to build a `NativeTypeExpander` from hooks for offline planning. | ||
|
|
||
| No centralized dispatch function is used. Each component declares its own expansion logic alongside its codec hook definitions. |
There was a problem hiding this comment.
Document the enforced validation/error behavior.
The ADR explains who expands parameterized types, but it does not mention the new enforcement semantics from this PR: invalid parameter sets are rejected, and missing expandNativeType support is an error rather than falling back to stringly rendering. That behavior is part of the contract of this design now, so it should be captured in either the decision or implementation notes.
As per coding guidelines, "Keep docs current (READMEs, rules, links) - see .cursor/rules/doc-maintenance.mdc."
Also applies to: 45-48
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md around lines 27 - 33, Update the ADR to document the enforced
validation/error semantics: state that CodecControlHooks.expandNativeType must
be provided for any codec that exposes parameterized native types, that missing
expandNativeType support is a hard error (no fallback to stringly rendering),
and that invalid parameter sets returned/encountered during expansion are
rejected with an error; mention where this enforcement applies (DDL/migrations
migration planner, schema verifier’s expected-type expansion, and
contractToSchema/NativeTypeExpander offline planning) and add the same text to
the implementation notes and decision sections (also apply the update to the
corresponding paragraphs around lines 45-48).
| - **Extensibility**: new parameterized types can follow the same pattern by adding an `expandNativeType` hook to their component's `controlPlaneHooks` — no adapter changes needed. | ||
| - **No adapter coupling**: the adapter does not reference extension-owned codecs. Each component owns its expansion logic. |
There was a problem hiding this comment.
Qualify the “no adapter changes needed” claim.
Line 39 overgeneralizes the consequence. This is true for extension-owned parameterized types, but new built-in adapter-owned native types still need adapter hook changes. Narrowing the wording here would keep the ADR from overstating the decoupling guarantee.
As per coding guidelines, "Keep docs current (READMEs, rules, links) - see .cursor/rules/doc-maintenance.mdc."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md around lines 39 - 40, Update the overgeneralized sentence about
adapter coupling to clarify that "no adapter changes needed" applies only to
extension-owned parameterized native types that implement an expandNativeType
hook on their controlPlaneHooks; state that adapter-owned built-in native types
still require adapter hook changes. Specifically, revise the two bullet points
referencing expandNativeType and controlPlaneHooks to narrowly qualify the
decoupling guarantee and mention adapter-owned native types as an exception so
the ADR no longer overstates the claim.
| ### Capability | ||
|
|
||
| A specific feature that a database may or may not support (e.g., `RETURNING` clauses, vector indexes). Your contract declares which capabilities it needs; the adapter reports which ones the database provides. Prisma Next checks these match at startup, so you find out about missing features immediately rather than at query time. | ||
|
|
There was a problem hiding this comment.
Describe capability matching as connect-time negotiation.
This currently says missing capabilities are checked "at startup", but the docs convention is adapter-reported capabilities negotiated when connecting. Tightening that wording will better match the architecture here.
✏️ Proposed wording
-A specific feature that a database may or may not support (e.g., `RETURNING` clauses, vector indexes). Your contract declares which capabilities it needs; the adapter reports which ones the database provides. Prisma Next checks these match at startup, so you find out about missing features immediately rather than at query time.
+A specific feature that a database may or may not support (e.g., `RETURNING` clauses, vector indexes). Your contract declares which capabilities it requires; the adapter reports which ones the connected database provides. Prisma Next negotiates those requirements at connect time, so you find out about missing features before queries run.As per coding guidelines, "Describe capabilities as adapter-reported and negotiated at connect time" and "Frame contract capabilities as requirements, not definitions".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/glossary.md` around lines 89 - 92, Update the "Capability" glossary
entry to describe capability matching as an adapter-reported, connect-time
negotiation rather than a startup check: rephrase the sentence that currently
says "Prisma Next checks these match at startup" to indicate that the adapter
reports provided capabilities at connect time and Prisma Next
negotiates/validates the contract's required capabilities against those provided
by the adapter when establishing the connection; ensure the wording frames the
contract's capabilities as requirements the contract declares and the adapter's
capabilities as what it provides.
| contract: prismaContract('./prisma/schema.prisma', { | ||
| output: 'src/prisma/contract.json', | ||
| }), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Provider implementation:"
sed -n '1,40p' packages/2-sql/2-authoring/contract-psl/src/provider.ts
echo
echo "Demo config call site:"
sed -n '1,30p' examples/prisma-next-demo/prisma-next.config.tsRepository: prisma/prisma-next
Length of output: 2415
Anchor the Prisma schema path to this config file.
prismaContract() resolves its schemaPath with resolve(schemaPath) in packages/2-sql/2-authoring/contract-psl/src/provider.ts:20, so ./prisma/schema.prisma is interpreted relative to the current working directory, not examples/prisma-next-demo/prisma-next.config.ts. Running the demo from the repo root will point at the wrong file or fail to read the schema.
🛠️ Suggested fix
+import { fileURLToPath } from 'node:url';
+
+const schemaPath = fileURLToPath(new URL('./prisma/schema.prisma', import.meta.url));
+
export default defineConfig({
family: sql,
target: postgres,
driver: postgresDriver,
adapter: postgresAdapter,
extensionPacks: [pgvector],
- contract: prismaContract('./prisma/schema.prisma', {
+ contract: prismaContract(schemaPath, {
output: 'src/prisma/contract.json',
}),📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| contract: prismaContract('./prisma/schema.prisma', { | |
| output: 'src/prisma/contract.json', | |
| }), | |
| import { fileURLToPath } from 'node:url'; | |
| const schemaPath = fileURLToPath(new URL('./prisma/schema.prisma', import.meta.url)); | |
| export default defineConfig({ | |
| family: sql, | |
| target: postgres, | |
| driver: postgresDriver, | |
| adapter: postgresAdapter, | |
| extensionPacks: [pgvector], | |
| contract: prismaContract(schemaPath, { | |
| output: 'src/prisma/contract.json', | |
| }), | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@examples/prisma-next-demo/prisma-next.config.ts` around lines 16 - 18, The
relative schema path passed to prismaContract is resolved from the process CWD,
so change the call to compute an absolute path anchored to this config file
(e.g. require('path').resolve(__dirname, './prisma/schema.prisma')) and pass
that resolved path into prismaContract (update the prismaContract(...)
invocation). This ensures prismaContract receives an absolute schemaPath
regardless of where the process is started.
| function expandPrecision({ nativeType, typeParams }: ExpandNativeTypeInput): string { | ||
| if (!typeParams || !('precision' in typeParams)) { | ||
| return nativeType; | ||
| } | ||
| const precision = typeParams['precision']; | ||
| if (!isPositiveInteger(precision)) { | ||
| throw new Error( | ||
| `Invalid "precision" type parameter for "${nativeType}": expected a positive integer, got ${JSON.stringify(precision)}`, | ||
| ); | ||
| } | ||
| return `${nativeType}(${precision})`; |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Does PostgreSQL allow a precision of 0 for timestamp, timestamptz, time, timetz, and interval type modifiers?
💡 Result:
Yes.
PostgreSQL’s date/time type modifiers allow an optional precision p (fractional digits in the seconds field) for:
timestamp(p)/timestamptz(p)time(p)/timetz(p)(i.e.,time [ (p) ] with/without time zone)interval(p)
…and the allowed range of p is 0 to 6, so (...)(0) is valid for all of the types you listed. [1]
Example: timestamp(0), timestamptz(0), time(0), timetz(0), interval(0). [1]
Sources
[1] PostgreSQL Documentation — Date/Time Types (datatype-datetime): precision p allowed range 0 to 6. (postgresql.org)
Citations:
Allow 0 precision for temporal type modifiers in expandPrecision().
expandPrecision() rejects precision 0 via isPositiveInteger(), but PostgreSQL allows precision values from 0 to 6 for temporal types: timestamp(0), timestamptz(0), time(0), timetz(0), and interval(0) are all valid. The corresponding precisionRenderer() already accepts 0, creating an inconsistency where the type-side code is more permissive than the control-plane hook. Split validation to allow non-negative integers for temporal codecs while keeping numeric precision strictly positive. Update companion tests in packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts accordingly.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts` around
lines 80 - 90, expandPrecision currently rejects precision 0 by using
isPositiveInteger; change validation to allow zero for PostgreSQL temporal
types. In the expandPrecision function (signature ExpandNativeTypeInput) detect
temporal native types ("timestamp", "timestamptz", "time", "timetz", "interval")
and validate precision with a non-negative integer check (allow 0) for those
types, while keeping the existing isPositiveInteger validation for other native
types; ensure the error message still includes the invalid value via
JSON.stringify. Also update the corresponding tests in
packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts to cover
precision 0 for the temporal codecs and maintain existing numeric tests.
closes TML-2039
Key snippets
Before / After — Vector type representation in contract storage
New — Provider merges framework metadata into PSL-emitted contracts
Intent
Bring PSL contract authoring to parity with TypeScript contract authoring for the behaviors exercised by the demo app: framework metadata (extension packs, capabilities), parameterized vector DDL, and FK constraint naming. The end goal is that
examples/prisma-next-democan switch between TS and PSL as its contract source with no behavioral difference — proven by a dual-mode emit test.Change map
CapabilitySource@relation(map: ...)parsingvector()factory nativeType fixexpandNativeTypecontrol-plane hook for vector(N)mapvector(1536)unquoted)The story
Lock in regressions with tests first. Before making fixes, new test cases and updated fixtures capture the precise failure modes (empty
extensionPacks/capabilities, parameterizednativeTypeshape, unsupported@relation(map: ...)).Fix the vector type representation across the stack. The root cause of the
"vector(1536)"DDL bug was a conflation of two concerns: the PSL interpreter embedded the dimension innativeType('vector(1536)') and settypeRef, which caused the planner'squoteIdentifierpath to produce"vector(1536)". The fix separates concerns:nativeTypeholds only the base type name,typeParamscarries parameters, and target adapter expansion reassembles them into SQL. This convention is recorded in ADR 170.Provide a control-plane
expandNativeTypehook for pgvector. The pgvector control descriptor now exposes anexpandNativeTypecodec hook, ensuring schema verification also expandsvector+length→vector(1536)consistently with the planner.Support
@relation(map: ...)for FK constraint naming. The interpreter's relation attribute parser is extended to accept themapargument, parse it as a quoted string, and flow it through theforeignKey()builder. The planner already usesforeignKey.namewhen present.Add framework metadata emission to the PSL provider. The interpreter produces contract IR without
extensionPacks/capabilities(it has no PSL surface for these). The provider merges them from explicit options (extensionPacks,capabilitySources), deep-merging and sorting keys for deterministic output.capabilitySourcesis typed asreadonly CapabilitySource[]with an exported interface.Switch the demo to PSL-first and prove dual-mode equivalence. The demo config switches from
typescriptContract(...)toprismaContract('./prisma/schema.prisma', ...). A second config (prisma-next.config.ts-contract.ts) preserves the TS path. Thetest:dual-modescript emits from each source in turn and runs the demo test suite against each, proving behavioral equivalence.Behavior changes & evidence
PSL-emitted contracts include extension pack metadata and capabilities: Before → the PSL provider emitted
extensionPacks: {}andcapabilities: {}. After → these are populated from explicit sources (pack exports, adapter descriptors) and deep-merged deterministically.mergeCapabilitiesFromSourceswith typedCapabilitySourcepgvector
vector(N)renders valid DDL: Before →nativeType: 'vector(1536)'+typeRefcaused"vector(1536)"(quoted identifier) in DDL. After →nativeType: 'vector'+typeParams: { length: 1536 }expands tovector(1536)(unquoted, valid SQL)."vector(1536)"as thevectorextension type with a dimension parameter; it treats it as a type name containing parentheses, which doesn't exist.vector()factoryexpandNativeTypehook for schema verificationvector(1536)unquoted@relation(map: "...")accepted and FK constraint name propagated: Before →mapargument on@relationproducedPSL_INVALID_RELATION_ATTRIBUTE. After → accepted, parsed as string, recorded in contract storage asforeignKeys[].name.mapto name FK constraints. Without support, valid schemas failed interpretation.mapargument parsing + FK builder wiringDemo switched from TS to PSL contract source (no behavior change to end users): The demo config now uses
prismaContract('./prisma/schema.prisma', ...). The similarity-search query no longer needs runtime type guards because the contract types are fully resolved.test:dual-modescript proves both modes passCompatibility / migration / risk
nativeTypechange from'vector(1536)'to'vector'changes storage hashes. Users must re-emit contracts viaprisma-next contract emit.extensionPacksandcapabilitiesare now populated where they were previously{}. Hash changes expected.@prisma-next/sql-contract-pslas a new dependency. The TS contract (prisma/contract.ts) remains for the no-emit workflow and dual-mode testing.Follow-ups / open questions
typeRef → quoteIdentifier(nativeType)path in the planner remains for non-parameterized named types (e.g., enums). Any future parameterized extension type that usestypeRefwould hit the same quoting issue — a systemic fix is deferred.capabilitySources) is deferred (spec Open Question 1).Non-goals / intentionally out of scope
Summary by CodeRabbit
New Features
Documentation