Repository navigation
TML-2956: migrate 7 SQL attributes to declarative attribute specs - #932
Conversation
|
Warning Review limit reached
Next review available in: 49 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (8)
📒 Files selected for processing (20)
📝 WalkthroughWalkthroughThis PR adds new PSL attribute-spec combinators and a model-level attribute factory, and rewires contract-psl to interpret model and field attributes through node-based specs. It also updates diagnostic expectations and removes legacy parsing helpers. ChangesPSL Attribute Combinators
SQL Attribute Interpretation Refactor
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@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.
🧹 Nitpick comments (1)
packages/2-sql/2-authoring/contract-psl/test/interpreter.test.ts (1)
786-787: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueAssertion is now code-only — consider keeping a message check.
The previous assertion matched a specific "missing colon" message via regex. The new assertion only checks
d.code === 'PSL_INVALID_ATTRIBUTE_SYNTAX', which is less precise — a regression in the diagnostic message content would go undetected. If the record combinator's message is stable, consider adding ad.messagecheck alongside the code assertion.🤖 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/test/interpreter.test.ts` around lines 786 - 787, The diagnostic assertion in interpreter.test.ts is now too broad because it only checks PSL_INVALID_ATTRIBUTE_SYNTAX and can miss regressions in the actual error text. Update the failing assertion around the record combinator parsing case in the relevant test so it also verifies d.message contains the expected “missing colon” wording (or equivalent stable text) alongside the existing code check. Keep the check scoped to the same result.failure.diagnostics.some(...) assertion used in the test.
🤖 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.
Nitpick comments:
In `@packages/2-sql/2-authoring/contract-psl/test/interpreter.test.ts`:
- Around line 786-787: The diagnostic assertion in interpreter.test.ts is now
too broad because it only checks PSL_INVALID_ATTRIBUTE_SYNTAX and can miss
regressions in the actual error text. Update the failing assertion around the
record combinator parsing case in the relevant test so it also verifies
d.message contains the expected “missing colon” wording (or equivalent stable
text) alongside the existing code check. Keep the check scoped to the same
result.failure.diagnostics.some(...) assertion used in the test.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 7113f90d-7157-4b17-863a-d841493cbd4f
⛔ Files ignored due to path filters (8)
projects/typed-attribute-parsers/slices/sql-attributes/dispatches/01-model-attribute-kit.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/sql-attributes/dispatches/02-map.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/sql-attributes/dispatches/03-id-unique.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/sql-attributes/dispatches/04-index.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/sql-attributes/dispatches/05-control.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/sql-attributes/dispatches/06-polymorphism.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/sql-attributes/plan.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/sql-attributes/spec.mdis excluded by!projects/**
📒 Files selected for processing (17)
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/bool.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/entity-ref.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/int.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/record.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/model-attribute.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-d.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.tspackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-psl/src/sql-attribute-specs.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.control-policy.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.test.tspackages/2-sql/2-authoring/contract-psl/test/psl-attribute-parsing.test.ts
💤 Files with no reviewable changes (2)
- packages/2-sql/2-authoring/contract-psl/test/psl-attribute-parsing.test.ts
- packages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.ts
86e1ce3 to
1344d43
Compare
…plan, D1 brief, review scaffold Signed-off-by: Serhii Tatarintsev <[email protected]>
Grow the attribute-spec kit so model-level attributes can be interpreted. - modelAttribute(name, config): model-level analogue of fieldAttribute, fixing level to 'model' with the same positional/named/refine shape and AttributeOut inference. - int(): parses an integer NumberLiteralExpr to number; non-integer or non-number arguments produce the standard leaf diagnostic. - bool(): parses a BooleanLiteralExpr to boolean; otherwise a leaf diagnostic. Unit and type-level tests cover success and diagnostic paths, and pin that modelAttribute infers the same shape as fieldAttribute. Signed-off-by: Serhii Tatarintsev <[email protected]>
Replace parseMapName with declarative modelAttribute/fieldAttribute specs interpreted through the combinator kit. Invalid @Map arguments now surface PSL_INVALID_ATTRIBUTE_SYNTAX instead of PSL_INVALID_ATTRIBUTE_ARGUMENT. Signed-off-by: Serhii Tatarintsev <[email protected]>
Lower the four SQL constraint attributes through the attribute-spec kit: field @id/@unique map name via optional(str()); model @@id/@@unique field list + map via list(fieldRef(self), { nonEmpty, unique }) + optional(str()). Split the shared @@unique/@@index interpreter branch: @@unique now routes through the spec while @@index stays on the legacy parseAttributeFieldList / findDuplicateFieldName / parseConstraintMapArgument path (migrates in D4). Semantic checks (nullable-in-PK, column mapping, both-inline-and-block PK, duplicate @@id declaration) remain in the interpreter. Argument-syntax errors now surface PSL_INVALID_ATTRIBUTE_SYNTAX with the kit messages; semantic diagnostics keep their existing codes. Signed-off-by: Serhii Tatarintsev <[email protected]>
Add the record(of) combinator to the psl-parser kit: it parses an
ObjectLiteralExprAst into a Record<string, T>, accumulating leaf
failures and rejecting non-object args, keyless/valueless fields, and
duplicate keys. Export leafDiagnostic so spec refines can build
consistent kit diagnostics.
Migrate @@index onto a declarative model spec (positional field list via
list(fieldRef(self), { nonEmpty, unique }); named map/type/options with
options: record(str()); options-requires-type in refine) and add the
interpretModelIndex helper. Index output is unchanged.
Delete the now-dead SQL syntax helpers subsumed by the kit:
parseObjectLiteralStringMap, splitObjectLiteralEntries, findTopLevelColon,
parseAttributeFieldList, parseFieldList, findDuplicateFieldName, and
parseConstraintMapArgument. Argument-syntax errors now surface
PSL_INVALID_ATTRIBUTE_SYNTAX; test assertions updated accordingly.
Signed-off-by: Serhii Tatarintsev <[email protected]>
…ist parity note Signed-off-by: Serhii Tatarintsev <[email protected]>
Lower @@control via a modelAttribute spec using oneOf(identifier(...)) for the policy word, replacing the hand-rolled parseControlPolicyAttribute. The duplicate-attribute guard stays in the interpreter. Argument-syntax errors now surface PSL_INVALID_ATTRIBUTE_SYNTAX with the kit messages. Delete the four control-policy helpers now that they have no callers. Signed-off-by: Serhii Tatarintsev <[email protected]>
…y note Signed-off-by: Serhii Tatarintsev <[email protected]>
… specs Add the entityRef kit combinator (bare model-name reference; existence resolved downstream) with unit tests. Lower @@Discriminator via fieldRef('self') and @@base via entityRef()+str() through the SQL attribute specs, threading sourceFile into collectPolymorphismDeclarations. The discriminator String-type check is retained; the now-unreachable PSL_DISCRIMINATOR_FIELD_NOT_FOUND block is removed (SQL only, Mongo untouched). Delete the dead singular getPositionalArgument helper. Signed-off-by: Serhii Tatarintsev <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…split @default to sql-default Signed-off-by: Serhii Tatarintsev <[email protected]>
…into generic wrappers Signed-off-by: Serhii Tatarintsev <[email protected]>
…tribute lookups
Replace the .path().join(".") AST stringify in findModelAttributeNode and
findFieldAttributeNode with a structural isSimpleName getter, avoiding the
re-stringify anti-pattern. Harden the malformed-options test to assert the
record combinator message substring.
Signed-off-by: Serhii Tatarintsev <[email protected]>
…relation Delete findRelationAttributeNode and buildRelationInterpretCtx from psl-relation-resolution and route @relation through the generic findFieldAttributeNode/interpretFieldAttribute helpers. Extend interpretFieldAttribute/buildFieldInterpretCtx with an optional resolveReferencedModel knob (defaulted to () => undefined) so map/id/unique callers are unaffected. Removes the last path().join AST-name stringify from the SQL src. Signed-off-by: Serhii Tatarintsev <[email protected]>
1344d43 to
69b7e7f
Compare
#938) ## Linked issue Refs [TML-2956](https://linear.app/prisma-company/issue/TML-2956) — "Language Tools Support Prisma Next PSL". Follow-up to #932 (the 7 non-`@default` SQL attributes). This PR finishes the SQL family: `@default` was split out of that slice because of its size, and lands here. With it, every SQL attribute's argument parsing is declarative — and `@default`'s spec is composed **dynamically per field**, so the grammar itself describes exactly which values are valid at each site. ## At a glance The `@default` spec is built per field from the field's resolved context (the composed default-function registry, `isList`, and — for enum fields — the enum's members), composed entirely from atomic combinators via `oneOf`: ```ts // non-enum field, from { isList, registry } oneOf( str(), num(), bool(), // flexible literals (codec still type-checks the value) ...(isList ? [list(oneOf(str(), num(), bool()))] : []), // list arm ONLY on list fields ...[...registry.entries()].map(([name, entry]) => // one typed arm per registered default function funcCall(name, entry.signature)), ) // enum field, from enumHandle.enumMembers oneOf(...enumMembers.map((m) => identifier(m.name))) // e.g. Expected one of: Low | High ``` Each default function now declares an **argument signature** built from combinators — so `uuid(4)` / `uuid(7)`, the required `cuid(2)`, `nanoid`'s `2..255` size, and `dbgenerated`'s string are parsed and range/shape-checked by the grammar, and each registry `lower` receives a **typed** `{ fn, span, args }` call instead of re-parsing argument source text: ```ts // adapter registry entry (postgres/sqlite) ['uuid', { signature: { positional: [{ key: 'version', type: optional(oneOf(num(4), num(7))) }] }, lower: (i) => i.call.args.version === 7 ? gen('uuidv7') : gen('uuidv4') }] ``` Previously `@default` was parsed by three hand-written string scanners (`parseDefaultLiteralValue`, `parseListDefaultExpression`, a ~160-line `parseDefaultFunctionCall`) **and** each registry `lower` re-parsed raw argument strings (`parseIntegerArgument`, `parseStringLiteral`, `expectNoArgs`, manual count checks). All of it is gone; the specs interpret the real AST and the `lower` bodies read typed args. ## Decision This PR makes `@default` spec-driven on both lowering paths and composes each spec dynamically per field: 1. **Dynamic non-enum spec** — `buildDefaultSpec({ isList, registry })` composes literal/list/function arms; the `list` arm exists only for list fields, and one `funcCall(name)` arm is emitted per registered default function. 2. **Dynamic enum spec** — `buildEnumDefaultSpec(members)` is `oneOf(identifier(member)…)`, so a bare member name is validated against the actual enum by the grammar. 3. **Kit** — `funcCall(name, signature)` (name-pinned, parallel to `identifier(name)`) parses a call's arguments through a recursive positional/named signature into a typed `{ fn, span, args }`; a general `num()` number-literal atom (any number incl. floats; `int({ min, max })` stays integer-only, now bounded); `str()`/`bool()`/`list()`/`oneOf()`/`identifier()`/`optional()` reused as-is. 4. **Typed function arguments (ADR 231).** Each SQL default function declares a `FuncCallSig`; the registry `lower` reads the typed args cast-free (`typeof`/literal comparisons), and the imperative arg parsers are deleted. Because `FuncCallSig` is authoring-layer and the core registry entry can't name it, `signature` is an opaque `unknown` on the entry, narrowed with one justified `blindCast<FuncCallSig>` in `buildDefaultSpec`. 5. **Validation lifted into the grammar** — unknown function name, unknown enum member, and now **argument shape / arity / range** are `PSL_INVALID_ATTRIBUTE_SYNTAX` grammar failures; array-on-scalar / scalar-on-list are grammar misses. The single surviving semantic arg check is `dbgenerated` empty → `PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT`. Each per-field spec becomes a precise description a future language server can read for autocomplete. 6. **Dead-code removal** — the three legacy string scanners, `funcCall`'s span-arithmetic chain, the monolithic `scalarLiteral()`/`bareIdentifier()` combinators, and the per-`lower` imperative arg parsers (`parseIntegerArgument`/`parseStringLiteral`/`expectNoArgs`) — all deleted (net −589 lines in the final commit). Only *argument syntax* moved to specs; the genuinely semantic rules stay in the interpreter. ## How it fits together 1. **Atomic combinators.** `str()`/`num()`/`bool()` are flexible literal leaves; `funcCall(name)` matches a call with an exact callee (raw args captured — the registry still validates them); `identifier(name)` matches an exact bare identifier. Array defaults reuse `list()`. 2. **The spec is assembled at interpretation time.** `lowerDefaultForField` calls `buildDefaultSpec({ isList, registry })`; `lowerEnumDefaultForField` calls `buildEnumDefaultSpec(enumHandle.enumMembers.map(m => m.name))`. Because the registry and field facts are in hand there, `oneOf(funcCall(name)…)` enumerates the open contributed function set — no bespoke `funcCallFrom` combinator needed (composition over special-casing, per ADR 231 principle 4). 3. **Interpreter keeps the semantics.** For a function value, the interpreter hands the typed call to `lowerDefaultFunctionWithRegistry` → `entry.lower`, which now reads typed args and keeps generator applicability + codec matching (`PSL_INVALID_DEFAULT_APPLICABILITY`) and the `dbgenerated`-empty check (`PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT`). Literal↔codec type is still enforced downstream by the codec's `encodeJson`. For enum, the interpreter maps the (grammar-validated) member name to its value. 4. **Grammar subsumes the shape/membership/arity checks.** With the list arm gated on `isList`, one `funcCall(name, sig)`/`identifier(member)` arm per known function/member, and each function's args range/shape-checked by its signature, an unknown function, unknown member, scalar-on-list, array-on-scalar, or malformed argument is just an unmatched `oneOf` — one uniform `PSL_INVALID_ATTRIBUTE_SYNTAX`. ## Behavior changes & evidence - **`@default` specs are composed per field.** The function set and enum-member set come from the field's context, so the spec describes exactly what's valid there. See [`sql-attribute-specs.ts`](packages/2-sql/2-authoring/contract-psl/src/sql-attribute-specs.ts) (`buildDefaultSpec`/`buildEnumDefaultSpec`); wired in [`psl-column-resolution.ts`](packages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.ts) + [`psl-field-resolution.ts`](packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts). - **Unknown function name and unknown enum member are now grammar failures** (`PSL_INVALID_ATTRIBUTE_SYNTAX`, `Expected one of: …`), replacing the post-validation `PSL_UNKNOWN_DEFAULT_FUNCTION` / `PSL_ENUM_UNKNOWN_DEFAULT_MEMBER`. Evidence in [`interpreter.defaults.test.ts`](packages/2-sql/2-authoring/contract-psl/test/interpreter.defaults.test.ts) + [`interpreter.enum.test.ts`](packages/2-sql/2-authoring/contract-psl/test/interpreter.enum.test.ts). - **`funcCall(name, signature)` parses typed args; `num(value)`/`int({min,max})` added.** `funcCall('now')` matches `now()` but not `foo.now()`; a signed call binds args into `{ fn, span, args }`. See [`func-call.ts`](packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/func-call.ts) + [`num.ts`](packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/num.ts); evidence in [`attribute-spec-combinators.test.ts`](packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts). - **Malformed function arguments are now grammar failures.** `uuid(5)`, `cuid()`, `nanoid(1)`, `dbgenerated(123)`, and args-on-nullary shift from `PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT` / `PSL_UNKNOWN_DEFAULT_FUNCTION` to `PSL_INVALID_ATTRIBUTE_SYNTAX` (operator "Option A"). Registry `lower` bodies read typed args and are cast-free. See [`default-function-registry.ts`](packages/2-sql/2-authoring/contract-psl/src/default-function-registry.ts), [`control-mutation-defaults.ts`](packages/3-targets/6-adapters/postgres/src/core/control-mutation-defaults.ts); evidence in [`interpreter.defaults.test.ts`](packages/2-sql/2-authoring/contract-psl/test/interpreter.defaults.test.ts) + the adapter `control-mutation-defaults.test.ts`. ## Reviewer notes - **`funcCallFrom` was never built.** `oneOf(...registry.keys().map(funcCall))`, composed at interpretation time, is the open-set dispatch the ADR proposed `funcCallFrom` for — with the matched arm as the `fn` discriminant. Composition over a bespoke combinator (ADR 231 principle 4). - **`matchingScalarLiteral` deferred; literals stay flexible.** Codec value-validation remains the codec's `encodeJson` (the single authority, shared with the TS builder); moving it into the grammar would need codec accept-schema metadata that doesn't exist yet. Recorded in the slice spec. - **`oneOf` variadic typing.** `buildDefaultSpec`/`buildEnumDefaultSpec` annotate the arms as a non-empty readonly tuple (`readonly [ArgType<T>, ...ArgType<T>[]]`) to satisfy `oneOf`'s constraint — no casts. - **Diagnostic-code shifts are intentional** (consistent with #932 / operator "Option A"): shape, membership, **and function-argument arity/range** errors → `PSL_INVALID_ATTRIBUTE_SYNTAX`; genuinely semantic codes (`PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT` for `dbgenerated` empty, `PSL_INVALID_DEFAULT_APPLICABILITY`) preserved. **Coarse-diagnostic trade-off (accepted per ADR 231):** a malformed argument on a callee-matched funcCall arm makes the outer `oneOf` backtrack to a generic `Expected one of: …` message, so `@default(uuid(5))` no longer gets a uuid-specific hint. `cuid()` loses its former "use `cuid(2)`" guidance for the same reason. - **⚠ Breaking change to the extension-authoring contract.** `ControlMutationDefaultEntry.lower` now receives a typed `TypedDefaultFunctionCall` (was `ParsedDefaultFunctionCall`), and an arg-bearing contributed default function must declare a `signature`. Any extension contributing default functions must migrate (the `default-pack-slugid` parity fixture was migrated as the in-repo example). Downstream-upgrade need recorded in the slice spec. - **Bundling fix:** `@prisma-next/psl-parser` promoted from a dev- to a runtime dependency of `adapter-postgres` so tsdown externalises (not bundles) the combinators — a bundled copy gave `num()`/`str()` private AST classes, failing `instanceof` against `sql-contract-psl`-parsed nodes so every valid argumented `@default` silently failed to parse. Invisible to source-resolved unit tests; caught only by the dist-consuming real-pack parity suite. - **ADR 231 left untouched** (operator instruction); the deviations (`funcCallFrom` dropped for `oneOf(funcCall(name, sig))`; `matchingScalarLiteral` deferred; typed-funcCall provenance) are recorded in the slice spec. - **Project artefacts** under `projects/typed-attribute-parsers/slices/sql-default/` are included for review provenance; migrated/removed at project close-out. ## Verification Run on final HEAD: - `pnpm --filter @prisma-next/framework-components build && typecheck && test` — clean; **469** tests - `pnpm --filter @prisma-next/psl-parser build && typecheck && test` — clean; **623** tests - `pnpm --filter @prisma-next/sql-contract-psl typecheck && test` — clean; **333** tests - `pnpm --filter @prisma-next/adapter-postgres typecheck && test` (+ coverage ≥ thresholds) — **675** tests - `pnpm --filter @prisma-next/adapter-sqlite typecheck && test` — **220** tests - Integration authoring parity (incl. dist-consuming real-pack `instanceof` parity + `@default` diagnostics fixtures) — **50** tests - `pnpm build` — 68/68 · `pnpm fixtures:check` — clean, no drift · `pnpm lint:framework-vocabulary` — 836/836 · `pnpm lint:deps` — 0 violations ## Follow-ups - Mongo family attribute + `@default` migration — the remaining slice of TML-2956. - Language-server autocomplete reading these per-field specs — the deferred LS-scoped work this dynamic design enables. ## Alternatives considered - **`funcCallFrom(registry)` as a dedicated combinator.** Rejected: with dynamic per-field construction the registry is in hand, so `oneOf(funcCall(name)…)` composes the same open-set dispatch without a bespoke combinator or dragging registry concerns into the kit. - **`matchingScalarLiteral()` / codec-typed literals now.** Rejected for this PR: literal↔type validation already lives at the codec's `encodeJson`; a spec-level matcher would duplicate it (drift risk) or need codec accept-schema metadata that doesn't exist. Deferred. - **Keeping `PSL_UNKNOWN_DEFAULT_FUNCTION` / `PSL_ENUM_UNKNOWN_DEFAULT_MEMBER` as semantic checks.** Rejected: folding membership into the grammar is the point (less post-validation), and `oneOf`'s "Expected one of: …" preserves the helpful supported-set message. - **Typing `signature` on the core entry as `FuncCallSig` (not `unknown`).** Rejected: `FuncCallSig` lives in the authoring layer (`@prisma-next/psl-parser`); the core `framework-components` entry type cannot name it without a layering violation (`pnpm lint:deps`). The opaque-`unknown` + single narrowing `blindCast` in the SQL family is the layer-clean shape; the typed `{fn,span,args}` call passed to `lower` is plain-structural and needs no cast. - **Keeping the imperative per-`lower` arg parsers.** Rejected: that is exactly the raw-string re-parse ADR 231's typed `funcCall` replaces; the signatures make arg validation a grammar concern and delete the parsers. ## 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; `@default` argument-syntax error *codes* consolidated (documented in the slice spec), no CLI/API/config surface change. --------- Signed-off-by: Serhii Tatarintsev <[email protected]>
Linked issue
Refs TML-2956 — "Language Tools Support Prisma Next PSL".
Second of three slices under that ticket. Builds on the attribute-spec kit +
@relationmigration shipped in #891 (slice 1).@defaultwas split mid-flight into a follow-up slicesql-default(see Reviewer notes).At a glance
SQL attributes now declare their argument grammar as data instead of hand-parsing it.
@@index, for example: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
@defaultspec-driven, and grows the shared attribute-spec kit with the combinators those attributes need:@map/@@map,@id/@unique,@@id/@@unique,@@index,@@control,@@discriminator,@@baseare now interpreted throughAttributeSpecs inpackages/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).@prisma-next/psl-parser) — amodelAttributeconstructor plusint,bool,record, andentityRefcombinators, each unit-tested in isolation before their first consumer landed.@default— the most complex attribute — was split into a follow-up slice rather than bundled here; see Reviewer notes.How it fits together
modelAttribute(mirroring the existingfieldAttribute) lets model-level@@attributes be specced;int/bool/record/entityRefare leaf combinators added right before the attribute that first needs them. Each ships with combinator unit tests inpackages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts.sql-attribute-specs.tsholds the specs plus smallinterpret*helpers that locate the attribute's AST node (findModelAttributeNode/findFieldAttributeNode), build the interpret context, runinterpretAttribute, and either return the typed result or push the kit's diagnostics.interpreter.tsandpsl-field-resolution.tscall those helpers instead of the legacy parsers. Where a legacy branch fused two attributes (the shared@@unique/@@indexfield-list path), it was split so each attribute migrates independently.rg-confirmed to have zero remaining callers — the@db.*native-type helpers and the three@default-only helpers are deliberately retained.Behavior changes & evidence
@map, non-list@@id, unknown@@indexoption, bad@@controlpolicy word) surfacePSL_INVALID_ATTRIBUTE_SYNTAXfrom the kit rather than the old per-parserPSL_INVALID_ATTRIBUTE_ARGUMENT. Semantic diagnostics keep their codes. Seesql-attribute-specs.ts; evidence ininterpreter.diagnostics.test.ts.@@indexobject-literal options are parsed structurally. The newrecord(str())combinator replaces the hand-rolled brace/colon scanner;options-requires-typemoved to the spec'srefine. Seecombinators/record.ts; evidence inattribute-spec-combinators.test.ts.@@discriminatorunknown-field now reportsPSL_INVALID_ATTRIBUTE_SYNTAX. Modelling the field viafieldRef('self')folds field-existence into the parse, unifying it with how@@id/@@unique/@@indexalready report unknown fields; the now-unreachable SQLPSL_DISCRIMINATOR_FIELD_NOT_FOUNDblock was removed. Seeinterpreter.ts; evidence ininterpreter.polymorphism.test.ts.@@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
psl-attribute-parsing.ts(−314) andinterpreter.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 ininterpreter.tsis the@@unique/@@indexbranch split — worth spot-checking that@@indexbehaviour is byte-for-byte preserved (it stays on the legacy path in this PR).@defaultdeliberately excluded. It introduces a novel registry-parameterisedfuncCallcombinator plus six preserved semantic codes; bundling it would push this PR past a single coherent review. It ships in the follow-up slicesql-default. Consequently the three@default-only helpers (parseDefaultLiteralValue,parseDefaultFunctionCall,parseListDefaultExpression) are retained here.@@indexrefinediagnostic anchors to the model node, not the attribute span. The kit'srefine(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.PSL_DISCRIMINATOR_FIELD_NOT_FOUNDand parsers remain — the Mongo family migrates in slice 3.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 testspnpm --filter @prisma-next/sql-contract-psl typecheck— clean; 283 testspnpm fixtures:check— clean, no contract/migration driftpnpm lint:framework-vocabulary— 906/906pnpm lint:deps— 0 layering violations (1169 modules cruised)Follow-ups
sql-defaultslice — migrate@default(funcCall/registry + literal/enum/list leaves), delete the three retained default helpers.Alternatives considered
@@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.@@discriminatorfield-existence as a dedicated semantic check (PSL_DISCRIMINATOR_FIELD_NOT_FOUND) by parsing only the bare name. Rejected in favour offieldRef('self')for consistency with the other model field-list attributes; the dedicated code became redundant.@defaultin this PR as the last dispatch. Rejected on size — its novel combinator surface and semantic-code count warranted its own reviewable slice.Checklist
git commit -s) per the DCO.TML-NNNN: <sentence-case title>form.Summary by CodeRabbit