Repository navigation
tml-2956: PSL attribute-spec kit + @relation migration (1/3) - #891
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:
📝 WalkthroughWalkthroughAdds attribute-spec parsing primitives and type inference utilities, re-exports them from ChangesAttribute-spec framework and relation migration
Foundation utility type exports
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/1-framework/2-authoring/psl-parser/src/attribute-spec/interpret.ts`:
- Around line 40-56: The named-argument loop in interpret should reject
duplicate keys instead of skipping them in silence. Update the duplicate check
around namedSeen in the attribute-spec parsing logic so that a repeated key
emits a structural diagnostic for the attribute and does not proceed as a
successful parse. Use the existing diagnostic pattern in interpret, and keep the
behavior aligned with the unknown-argument handling for spec.name and namedArgs.
In `@packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts`:
- Around line 141-142: The relation list schema still permits duplicate column
names, which can let repeated FK entries flow into foreign key resolution.
Update the `fields` and `references` definitions in `psl-relation-resolution` to
enforce uniqueness by adding the list-level uniqueness constraint alongside the
existing `nonEmpty` validation. Keep the change localized to the relation
parsing schema so `foreignKeyNodes` only receives deduplicated names.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 32be81a6-69d0-4823-9438-44961008ee55
⛔ Files ignored due to path filters (6)
projects/typed-attribute-parsers/plan.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/attribute-spec-kit/dispatches/02-combinators.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/attribute-spec-kit/dispatches/03-migrate-relation.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/attribute-spec-kit/plan.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/attribute-spec-kit/spec.mdis excluded by!projects/**projects/typed-attribute-parsers/spec.mdis excluded by!projects/**
📒 Files selected for processing (17)
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/diagnostic.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/enum-of.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/field-ref.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/identifier-name.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/list.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/field-attribute.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/interpret.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/optional.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/types.tspackages/1-framework/2-authoring/psl-parser/src/exports/index.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test-d.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec.test-d.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec.test.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts
| if (result.ok) namedParsed.set(key, result.value); | ||
| } | ||
|
|
||
| const positionalSeen = new Set<string>(); |
There was a problem hiding this comment.
This is way to complicated for what it is supposed to be doing? Why are we doing one pass over positional args, one pass over named arguments, then merging the two in a separate pass? Just produce a single map in one pass and report duplicates as you go.
There was a problem hiding this comment.
This is not addressed. Parsing is still done in 3 passes. With a separate maps for positional and named arguments, each bracnh handling it's duplication code, plus merging the 2 handling merge as well.
I want both positional and named passes to write intou output directly without intermediate maps and merge step. Named arg can conflict with positional arg key and it should produce an error.
| type Simplify<T> = { [K in keyof T]: T[K] } & {}; | ||
|
|
||
| type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ( | ||
| k: infer I, | ||
| ) => void | ||
| ? I | ||
| : never; |
There was a problem hiding this comment.
I am pretty sure we already have these helpers defined in several places. Reuse them
| readonly key: string; | ||
| readonly type: Param<T>; | ||
| /** A trailing rest slot that consumes every remaining positional argument. */ | ||
| readonly variadic?: boolean; |
There was a problem hiding this comment.
Do we really have variadic positional arguments anywhere?
| * default when the argument is absent; without one, an absent argument leaves | ||
| * the output property unset. | ||
| */ | ||
| export function optional<T>(type: ArgType<T>, ...rest: [defaultValue: T] | []): OptionalParam<T> { |
There was a problem hiding this comment.
Why isn't this an ArgType on it's own?
There was a problem hiding this comment.
this was not addressed
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts (1)
128-129: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winPreserve duplicate relation-list behavior.
Adding
unique: truerejects duplicate names infields/references, which tightens behavior relative to the legacy relation parser; the downstream test atpackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.tsLines 389-417 now codifies that stricter behavior. Remove the uniqueness constraint here.Proposed adjustment
- fields: optional(list(fieldRef('self'), { nonEmpty: true, unique: true })), - references: optional(list(fieldRef('referenced'), { nonEmpty: true, unique: true })), + fields: optional(list(fieldRef('self'), { nonEmpty: true })), + references: optional(list(fieldRef('referenced'), { nonEmpty: true })),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts` around lines 128 - 129, The relation-list validation in psl-relation-resolution should preserve the legacy ability to repeat names, so remove the unique: true constraint from both fields and references in the relation parser schema. Update the schema definition around the fields/references list handling in psl-relation-resolution so it only enforces nonEmpty where needed, and keep the existing relation resolution flow unchanged. Use the existing identifiers optional(list(...)), fieldRef('self'), and fieldRef('referenced') to locate the exact validation rules to adjust.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts`:
- Around line 87-88: The referential-action validation in
normalizeReferentialAction is now bypassed by enumOf, causing unsupported
onDelete/onUpdate values to surface as PSL_INVALID_RELATION_ATTRIBUTE instead of
the legacy unsupported-action diagnostic. Restore the old diagnostic parity by
moving the unsupported-value check into the downstream normalizer path used by
normalizeReferentialAction, or add a per-argument diagnostic override in the
relation attribute parsing flow so the specific unsupported referential-action
code is preserved.
---
Duplicate comments:
In `@packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts`:
- Around line 128-129: The relation-list validation in psl-relation-resolution
should preserve the legacy ability to repeat names, so remove the unique: true
constraint from both fields and references in the relation parser schema. Update
the schema definition around the fields/references list handling in
psl-relation-resolution so it only enforces nonEmpty where needed, and keep the
existing relation resolution flow unchanged. Use the existing identifiers
optional(list(...)), fieldRef('self'), and fieldRef('referenced') to locate the
exact validation rules to adjust.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: f5ca7493-831e-4d57-aaed-4fb80a8a2ce5
⛔ Files ignored due to path filters (2)
projects/typed-attribute-parsers/plan.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/attribute-spec-kit/dispatches/04-address-review-r1.mdis excluded by!projects/**
📒 Files selected for processing (10)
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/enum-of.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/field-ref.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/list.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/interpret.tspackages/1-framework/2-authoring/psl-parser/src/exports/index.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec.test.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
💤 Files with no reviewable changes (1)
- packages/1-framework/2-authoring/psl-parser/src/exports/index.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/field-ref.ts
- packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/enum-of.ts
- packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/list.ts
- packages/1-framework/2-authoring/psl-parser/test/attribute-spec.test.ts
- packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/one-of.ts`:
- Around line 16-19: The oneOf() combinator currently accepts zero alternatives,
which allows construction of an impossible ArgType<never> that only fails at
runtime. Update the oneOf function signature in one-of.ts to require a non-empty
rest tuple for alts, so callers must pass at least one ArgType; keep the
existing label-building logic in oneOf and ensure the type still resolves
through OutOf<Alts[number]> for valid non-empty inputs.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 8f4b5a02-bb68-4926-8296-3e5eee0629d8
⛔ Files ignored due to path filters (2)
projects/typed-attribute-parsers/plan.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/attribute-spec-kit/dispatches/06-oneof-identifier.mdis excluded by!projects/**
📒 Files selected for processing (6)
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/identifier.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/one-of.tspackages/1-framework/2-authoring/psl-parser/src/exports/index.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test-d.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.tspackages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts
e679570 to
e120376
Compare
| ); | ||
| continue; | ||
| } | ||
| if (seen.has(name)) { |
There was a problem hiding this comment.
Can't you check this once at the start of the loop instead of doing separate check for named and positional args?
const key = param.key ?? arg.name()
if (seen.has(name)) {
...
}
| ); | ||
| continue; | ||
| } | ||
| seen.set(name, 'named'); |
There was a problem hiding this comment.
Why does it matter if the argument is named?
96d3ddf to
3017855
Compare
…nference Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add diagnosticCode to InterpretCtx and have interpretAttribute populate a leaf-facing context from the spec before each leaf parse, so a leaf emits with the attribute code rather than a hard-coded generic. Signed-off-by: Serhii Tatarintsev <[email protected]>
Author the domain combinators @relation needs as ArgTypes over the expression AST, beside the attribute-spec engine, and export them from the package surface. enumOf types a homogeneous or mixed string/number set via a const tuple and a membership type-guard (no arktype: the value is already a parsed primitive and the check is a trivial closed set). fieldRef returns the bare name and carries scope metadata, deliberately leaving field-existence validation to the downstream interpreter. list lifts an element combinator over an array literal with nonEmpty/unique. Leaves emit through a shared helper stamped with ctx.diagnosticCode. Signed-off-by: Serhii Tatarintsev <[email protected]>
…fine specs The SQL @relation spec parses bare-identifier referential actions (onDelete: Cascade) whose set is validated downstream, so it needs a leaf that reads an IdentifierAst to its name with no parse-time check — fieldRef minus the resolution scope. Add identifierName() and export it. InferAttr previously constrained its parameter to AttributeSpec<unknown>, but Out sits contravariantly in AttributeSpec.refine, so any refine- carrying spec is not assignable to AttributeSpec<unknown> and the constraint rejected it. Drop the constraint; inference still recovers Out precisely. Adds a type-test for a refine-carrying spec. Signed-off-by: Serhii Tatarintsev <[email protected]>
…ttribute spec Replace the hand-written parseRelationAttribute with a sqlRelation AttributeSpec interpreted through the kit. The engine binds the positional-or-named name, fields/references field lists, map, and the bare-identifier onDelete/onUpdate; a refine holds the fields/references both-or-neither rule. Referential-action set validation stays downstream in normalizeReferentialAction (unchanged), preserving its code and span. interpretRelationAttribute assembles the InterpretCtx from interpreter state (declaring model, field, symbol table, source file) and maps the inferred output onto ParsedRelationAttribute. The three @relation call sites in interpreter.ts route through it; BuildModelNodeInput gains the source file and symbol table to assemble the context. Diagnostic codes and spans stay byte-identical for every @relation error path: the relations, many-to-many, and diagnostics suites pass unchanged and fixtures:check is clean. parseRelationAttribute is deleted; the helpers it used remain (other callers). Signed-off-by: Serhii Tatarintsev <[email protected]>
…n, review, briefs) Drive project/slice paper trail for the attribute-spec-kit slice: project spec + plan, slice spec + dispatch plan, dispatch briefs (D2/D3), and the code-review log. Transient project artifacts (removed at project close); no source references them. Signed-off-by: Serhii Tatarintsev <[email protected]>
A named key supplied twice, or a key supplied both positionally and by name, is now always a structural error — previously a duplicate named key was silently dropped and a positional/named alias only conflicted when the values differed. Drop the now-dead argValuesEqual/isPlainRecord helpers. Signed-off-by: Serhii Tatarintsev <[email protected]>
Drop the ParsedRelationAttribute rename wrapper that mapped name->relationName and map->constraintName. interpretRelationAttribute now returns the spec output (SqlRelationOutput); the interpreter reads name and map directly. Signed-off-by: Serhii Tatarintsev <[email protected]>
…ification) Signed-off-by: Serhii Tatarintsev <[email protected]>
Remove added comments that narrate a body, restate a signature/type, enumerate usages, or reference removed/overruled code; trim mixed comments down to the non-obvious "why". Comment-only change — no code, type, or behaviour is touched. Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…ibute Resolve (key, param) per positional/named branch, then run a single seen check that emits one uniform duplicate diagnostic anchored to the offending arg node. Drop the Origin type (seen is now a Set<string>) and duplicateDiagnostic entirely; the named-vs-positional distinction no longer affects the message or span. Alias-collision diagnostics now anchor to the duplicate arg node rather than the whole attribute. Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
… type-bound comment Remove the never-read `symbols: SymbolTable` field from `InterpretCtx` (combinators resolve via `selfModel` / `resolveReferencedModel()`), drop it from the ctx built in `buildRelationInterpretCtx` and the two test ctx helpers, and stop importing `SymbolTable` where it is now unused. Reword the `InferAttr` doc comment to say "type bound" instead of "constraint", since it describes a TypeScript generic bound, not an SQL constraint. These remove two false-positive hits from the framework-vocabulary ratchet. The one irreducible residual is the framework-neutral `../symbol-table` module path (matches "table"), which cannot go without renaming a shared module; the ratchet requires count === threshold, so bump the threshold 967 -> 968 by exactly that residual. No behaviour change. Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add optional per-scope `allow` compounds to lint-framework-vocabulary. A forbidden-term match is ignored when its matched token range is fully contained within an allowed compound range on the same line, so `SymbolTable`/`symbol-table` stop being false-positive `table` hits while a bare `table` elsewhere still counts. Absent `allow` preserves existing behaviour. Allow `SymbolTable` in packages/1-framework and recompute the threshold to the accurate count (968 to 906; 62 shielded lines). Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
3017855 to
4eaf232
Compare
| import { leafDiagnostic } from './diagnostic'; | ||
|
|
||
| /** | ||
| * Pinned-only: there is no open form, so several `identifier`s composed under |
There was a problem hiding this comment.
Wtf is pinned only? Wtf is open form? Why doc for oneOf is in indentifier method?
| } | ||
|
|
||
| /** | ||
| * When the referenced model is out of scope (e.g. a cross-space target the |
There was a problem hiding this comment.
This does not belong to doc comment
| import { leafDiagnostic } from './diagnostic'; | ||
|
|
||
| /** | ||
| * Because leaves are `Result`-pure — a failed branch returns its diagnostics |
…mments Move the genuine non-obvious rationale from JSDoc doc-headers onto the exact lines that implement each behaviour, in plain language, and drop headers that merely narrated or documented another symbol. The diagnosticCode why moves onto interpretAttribute's leafCtx line; oneOf's fallthrough, fieldRef's existence guard, and the InferAttr contravariance bound each carry a terse inline note. Comment-only: no code, signature, or behaviour change. Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
| import type { ArgType } from '../types'; | ||
| import { leafDiagnostic } from './diagnostic'; | ||
|
|
||
| // `const N` keeps each name's literal type, so `oneOf(identifier('a'), identifier('b'))` infers `'a' | 'b'`. |
There was a problem hiding this comment.
This just explains how TS works, no need to explain that.
| export function leafDiagnostic(ctx: InterpretCtx, node: AstNode, message: string): PslDiagnostic { | ||
| return { | ||
| // every leaf routes through here, so none hard-codes a code — use the attribute's, set on ctx by interpretAttribute. | ||
| code: ctx.diagnosticCode, |
There was a problem hiding this comment.
Why do we need diagnosticCode to be customizable? Can't we just unite on a single PSL_INVALID_ATTRIBUTE?
| ); | ||
| } | ||
| } | ||
| // Each alternative returns its own diagnostics instead of writing to a shared list, so a failed attempt leaves nothing behind; if none match, report one aggregate error. |
There was a problem hiding this comment.
This comment doesn't add value on top code
Remove the per-attribute diagnosticCode customization from the attribute-spec kit. AttributeSpec.diagnosticCode and InterpretCtx.diagnosticCode are deleted along with the leafCtx threading in interpretAttribute; structural and leaf diagnostics now stamp one constant, ATTRIBUTE_DIAGNOSTIC_CODE (PSL_INVALID_ATTRIBUTE_SYNTAX), and ctx is passed unchanged to leaves and refine. sqlRelation no longer sets a per-attribute code and relationInvariants + buildRelationInterpretCtx drop PSL_INVALID_RELATION_ATTRIBUTE, so @relation error paths routed through the engine now report the unified code. The interpreter.ts semantic relation checks keep their own codes and messages. Also purge comments that explain via a not-taken alternative (the const N note, the oneOf shared-list fallthrough note, the ArgType.parse shared-list note, and the leaf/ctx code-threading notes). Contract output is unchanged; only diagnostic codes in @relation error tests move to the unified code. Signed-off-by: Serhii Tatarintsev <[email protected]>
…ment purge Signed-off-by: Serhii Tatarintsev <[email protected]>
## Linked issue Refs [TML-2956](https://linear.app/prisma-company/issue/TML-2956) — "Language Tools Support Prisma Next PSL". Second of three slices under that ticket. Builds on the attribute-spec kit + `@relation` migration shipped in #891 (slice 1). `@default` was split mid-flight into a follow-up slice `sql-default` (see Reviewer notes). ## At a glance SQL attributes now declare their argument grammar as data instead of hand-parsing it. `@@index`, for example: ```ts const indexModelSpec = modelAttribute('index', { positional: [{ key: 'fields', type: list(fieldRef('self'), { nonEmpty: true, unique: true }) }], named: { map: optional(str()), type: optional(str()), options: optional(record(str())) }, refine: (value, ctx) => value.options !== undefined && value.type === undefined ? [leafDiagnostic(ctx, ctx.selfModel.node, '`@@index` options argument requires a type argument')] : [], }); ``` Previously each attribute had a bespoke string-scanning parser (`parseAttributeFieldList`, `parseObjectLiteralStringMap`, `parseControlPolicyAttribute`, …) that re-tokenised already-parsed PSL text by hand. The kit interprets the real AST, so field-existence, list non-emptiness, uniqueness, and object-literal shape all fall out of the combinators. ## Decision This PR makes every SQL attribute except `@default` spec-driven, and grows the shared attribute-spec kit with the combinators those attributes need: 1. **Migrated attributes** — `@map`/`@@map`, `@id`/`@unique`, `@@id`/`@@unique`, `@@index`, `@@control`, `@@discriminator`, `@@base` are now interpreted through `AttributeSpec`s in `packages/2-sql/2-authoring/contract-psl/src/sql-attribute-specs.ts`. Only *argument syntax* moved to specs; the interpreter keeps every *semantic* check (column mapping, applicability, duplicate-attribute guards, polymorphism resolution). 2. **Kit growth** (in `@prisma-next/psl-parser`) — a `modelAttribute` constructor plus `int`, `bool`, `record`, and `entityRef` combinators, each unit-tested in isolation before their first consumer landed. 3. **Dead-code removal** — ten hand-written string-parsing helpers deleted once their last caller migrated, net **−711 lines** in the SQL package's parsing surface. `@default` — the most complex attribute — was split into a follow-up slice rather than bundled here; see Reviewer notes. ## How it fits together 1. **Grow the kit first.** `modelAttribute` (mirroring the existing `fieldAttribute`) lets model-level `@@` attributes be specced; `int`/`bool`/`record`/`entityRef` are leaf combinators added right before the attribute that first needs them. Each ships with combinator unit tests in `packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts`. 2. **SQL-side plumbing.** `sql-attribute-specs.ts` holds the specs plus small `interpret*` helpers that locate the attribute's AST node (`findModelAttributeNode`/`findFieldAttributeNode`), build the interpret context, run `interpretAttribute`, and either return the typed result or push the kit's diagnostics. 3. **Route the interpreter.** `interpreter.ts` and `psl-field-resolution.ts` call those helpers instead of the legacy parsers. Where a legacy branch fused two attributes (the shared `@@unique`/`@@index` field-list path), it was split so each attribute migrates independently. 4. **Delete the dead helpers.** After each attribute's last caller moved to a spec, its parser was removed and `rg`-confirmed to have zero remaining callers — the `@db.*` native-type helpers and the three `@default`-only helpers are deliberately retained. ## Behavior changes & evidence - **Attribute-argument syntax errors now report a single unified code.** Malformed arguments (non-string `@map`, non-list `@@id`, unknown `@@index` option, bad `@@control` policy word) surface `PSL_INVALID_ATTRIBUTE_SYNTAX` from the kit rather than the old per-parser `PSL_INVALID_ATTRIBUTE_ARGUMENT`. Semantic diagnostics keep their codes. See [`sql-attribute-specs.ts`](packages/2-sql/2-authoring/contract-psl/src/sql-attribute-specs.ts); evidence in [`interpreter.diagnostics.test.ts`](packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts). - **`@@index` object-literal options are parsed structurally.** The new `record(str())` combinator replaces the hand-rolled brace/colon scanner; `options`-requires-`type` moved to the spec's `refine`. See [`combinators/record.ts`](packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/record.ts); evidence in [`attribute-spec-combinators.test.ts`](packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts). - **`@@discriminator` unknown-field now reports `PSL_INVALID_ATTRIBUTE_SYNTAX`.** Modelling the field via `fieldRef('self')` folds field-existence into the parse, unifying it with how `@@id`/`@@unique`/`@@index` already report unknown fields; the now-unreachable SQL `PSL_DISCRIMINATOR_FIELD_NOT_FOUND` block was removed. See [`interpreter.ts`](packages/2-sql/2-authoring/contract-psl/src/interpreter.ts); evidence in [`interpreter.polymorphism.test.ts`](packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts). - **Two attribute spellings intentionally narrowed to their canonical forms** — the named `@@index(fields: […])` form (positional-only now) and the quoted `@@control("external")` form (bare-identifier only). Both are invisible in practice: no in-repo schema, fixture, or example uses either. Rationale recorded in the slice spec. ## Reviewer notes - **Largest diff: `psl-attribute-parsing.ts` (−314) and `interpreter.ts` (±279).** The former is almost entirely deletions (the retired parsers); the latter is the branch-by-branch routing to specs. The one non-mechanical change in `interpreter.ts` is the `@@unique`/`@@index` branch split — worth spot-checking that `@@index` behaviour is byte-for-byte preserved (it stays on the legacy path in this PR). - **`@default` deliberately excluded.** It introduces a novel registry-parameterised `funcCall` combinator plus six preserved semantic codes; bundling it would push this PR past a single coherent review. It ships in the follow-up slice `sql-default`. Consequently the three `@default`-only helpers (`parseDefaultLiteralValue`, `parseDefaultFunctionCall`, `parseListDefaultExpression`) are retained here. - **`@@index` `refine` diagnostic anchors to the model node, not the attribute span.** The kit's `refine(value, ctx)` signature carries no attribute node; no test asserts that span, so parity holds. Widening the signature is a future kit tidy-up, not in scope. - **Mongo is untouched.** Its own `PSL_DISCRIMINATOR_FIELD_NOT_FOUND` and parsers remain — the Mongo family migrates in slice 3. - **Project artefacts on disk.** `projects/typed-attribute-parsers/slices/sql-attributes/` (spec, plan, per-dispatch briefs) is included for review provenance and will be migrated/removed at project close-out. ## Verification Run on final HEAD: - `pnpm --filter @prisma-next/psl-parser build && typecheck` — clean; **584** tests - `pnpm --filter @prisma-next/sql-contract-psl typecheck` — clean; **283** tests - `pnpm fixtures:check` — clean, no contract/migration drift - `pnpm lint:framework-vocabulary` — 906/906 - `pnpm lint:deps` — 0 layering violations (1169 modules cruised) ## Follow-ups - `sql-default` slice — migrate `@default` (funcCall/registry + literal/enum/list leaves), delete the three retained default helpers. - Mongo attribute migration — slice 3. ## Alternatives considered - **Preserve the named `@@index(fields: […])` and quoted `@@control("external")` spellings** by declaring the arg in both positional and named forms. Rejected: the engine supports it, but it carries dual-spelling complexity forever for forms no in-repo schema uses; the canonical positional/bare-identifier forms are what Prisma emits. - **Keep `@@discriminator` field-existence as a dedicated semantic check** (`PSL_DISCRIMINATOR_FIELD_NOT_FOUND`) by parsing only the bare name. Rejected in favour of `fieldRef('self')` for consistency with the other model field-list attributes; the dedicated code became redundant. - **Ship `@default` in this PR as the last dispatch.** Rejected on size — its novel combinator surface and semantic-code count warranted its own reviewable slice. ## Checklist - [x] All commits are signed off (`git commit -s`) per the DCO. - [x] I read CONTRIBUTING.md and the change is scoped to one logical concern. - [x] Tests are updated. - [x] The PR title is in `TML-NNNN: <sentence-case title>` form. - [x] Skill update: n/a — internal refactor; no user-facing CLI/API/config/error-code surface changed (attribute-syntax error *codes* consolidated, documented in the slice spec). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for additional PSL attribute value types: booleans, integers, model name references, and record/object arguments. * Introduced model-level attribute specifications to improve how model annotations are parsed and interpreted. * **Bug Fixes** * Improved PSL syntax validation and normalized diagnostic codes/messages for invalid or duplicate inputs across constraints, mappings, indexing, control policies, and polymorphism. * Enhanced attribute interpretation to be more syntax-accurate for better span reporting. * **Tests** * Expanded and updated coverage for the new value types, model-level behavior, and updated diagnostic expectations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Serhii Tatarintsev <[email protected]>
What this is
Slice 1 of 3 implementing ADR 231 — Declarative attribute specifications, scoped to the family interpreters. It stands up the declarative-attribute engine in
psl-parserand proves it end-to-end by migrating the SQL@relationattribute off its hand-written parser.Language-server integration (completion, go-to-definition over attribute arguments) is the follow-up this unblocks — and the reason the work lands under the Language Tools Support Prisma Next PSL project — but is not in scope here.
Why
Each family interpreter validated attribute arguments with hand-written code that pulled raw text out of the AST and re-checked its shape —
split(',')on field lists, ad-hoc quoted-string unwrapping, per-attribute unknown-argument rejection — duplicated across the SQL and Mongo interpreters. The output type drifted freely from the validation, and no other consumer (the language server) could read what an attribute accepts. ADR 231 replaces that with one declarativeAttributeSpecper attribute, read byinterpretAttribute, with the output type inferred from the spec.What's in this slice
psl-parser—ArgType,AttributeSpec,optional/fieldAttribute,interpretAttribute,InferAttr,InterpretCtx— consuming the parser'sExpressionAstCST directly.@relationneeds —str,enumOf,fieldRef(scope),list({ nonEmpty, unique }), plus a smallidentifierNameleaf for bare-identifier enum values.@relationmigrated to a declarativesqlRelationspec lowered throughinterpretAttribute; the hand-writtenparseRelationAttributeis deleted.Key decisions
ExpressionAstdirectly — no new intermediate argument representation. The CST already carries native literals and real spans.psl-parser, which already ownsExpressionAstand theSymbolTable. No new package.InterpretCtx.diagnosticCode— the engine threads the spec's code (herePSL_INVALID_RELATION_ATTRIBUTE) to every leaf, so codes stay byte-identical.onDelete/onUpdatekeepnormalizeReferentialActionas validator — they parse to the raw identifier name (no parse-time set check), preserving the existingPSL_UNSUPPORTED_REFERENTIAL_ACTIONcode + span.enumOfis intentionally not used for them.@relationleaf spans — strictly more precise, exercised by no fixture); messages may adopt the kit's phrasing; malformed inputs legacy tolerated by coincidence (a quotedonDelete: "Cascade") are now rejected. The span + message + stricter-rejection relaxations were explicitly ratified.Deliberately out of scope
Other SQL attributes (
@id,@unique,@@index,@default,@map,@@control,@@discriminator,@@base) → slice 2. All Mongo attributes → slice 3. The rest of ADR 231's combinator alphabet (int,bool,json,map,record,entityRef,codecRef,oneOf,funcCall,modelAttribute,blockAttribute) is added as later slices need it.@db.*native types and the TypeScript builder surface are out of the whole project.Validation
psl-parser: 504 tests pass (engine + combinators + type-level inference); typecheck + lint clean.@prisma-next/sql-contract-psl: 271 tests pass — the@relationrelations + diagnostics suites pass with zero test edits.pnpm fixtures:checkclean (no contract/migration drift); cross-packagepnpm typecheck143/143.Refs: TML-2956 · ADR 231 (#889).
Summary by CodeRabbit
nonEmpty/unique, optional values, andoneOfalternatives), plus field-level helpers and public exports to support authoring/interpretation.oneOf(identifier(...))usage.