Repository navigation
ADR 231: Declarative attribute specifications - #889
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughAdds ADR 231 proposing a declarative, composable attribute-specification model for PSL, with shared typing, parsing, and language-server behavior for attribute arguments. ChangesADR 231: Declarative Attribute Specifications
Estimated code review effort🎯 2 (Simple) | ⏱️ ~15 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md (1)
255-255: 📐 Maintainability & Code Quality | 🔵 TrivialClarify static vs. runtime type for
matchingScalarLiteral().The open question notes the "static output stays the general default-value union" because the field type isn't known where the spec is defined. Consider whether this is a fundamental limitation or could be addressed by making specs parametric on field type (e.g.,
fieldAttribute<T>(...)), or if the runtime check is an acceptable tradeoff. Worth a brief note in the ADR if this tension is intentional.🤖 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 `@docs/architecture` docs/adrs/ADR 231 - Declarative attribute specifications.md at line 255, Clarify the type-modeling choice around matchingScalarLiteral() by explicitly noting whether the general default-value union is a fundamental limitation or an intentional tradeoff. Update the ADR section that discusses matchingScalarLiteral() and the fieldAttribute/spec definition to mention the possibility of parametric typing (for example, a generic fieldAttribute<T>(...)) versus keeping the runtime check via ctx.field, and state which approach is intended.
🤖 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 `@docs/architecture` docs/adrs/ADR 231 - Declarative attribute
specifications.md:
- Line 255: Clarify the type-modeling choice around matchingScalarLiteral() by
explicitly noting whether the general default-value union is a fundamental
limitation or an intentional tradeoff. Update the ADR section that discusses
matchingScalarLiteral() and the fieldAttribute/spec definition to mention the
possibility of parametric typing (for example, a generic fieldAttribute<T>(...))
versus keeping the runtime check via ctx.field, and state which approach is
intended.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 6cc23473-b1cb-4a0e-addc-bf83c4bbc92c
📒 Files selected for processing (1)
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md
wmadden
left a comment
There was a problem hiding this comment.
Looks good! A couple of small notes below
|
|
||
| **Scalars** read a single token. `str()` parses a quoted string. `int({ min, max })` parses a number. `bool()` parses a boolean. `enumOf(...values)` parses a member of a fixed literal set — and because a member may be a string or a number, the set may be homogeneous *or* mixed. Mongo's index `type`, which accepts the numbers `1`/`-1` and the strings `"text"`/`"2dsphere"`/`"2d"`/`"hashed"`, is a single `enumOf(1, -1, 'text', '2dsphere', '2d', 'hashed')`. `json()` reads an opaque JSON value from a quoted string; it is the one place a structured value is text-encoded (see [Surface policy](#surface-policy-native-literals-with-one-text-exception)). | ||
|
|
||
| **References** resolve a name against something in the surrounding contract, so they depend on the [resolution context](#resolution-context). `fieldRef(scope)` resolves a field name, where `scope` is `'self'` (a field of the model declaring the attribute), `'referenced'` (a field of a relation's target model), or `'document'` (a free path, for wildcard projections). `modelRef()` resolves a model name. `codecRef()` resolves a registered codec id. |
There was a problem hiding this comment.
This should be generalized to a reference to any entity, since the contract can already contain arbitrary pack-contributed entity types, not just to model/field.
Propose a declarative spec for field/model/block PSL attributes, composed from a fixed combinator kit and interpreted into a strongly-typed object whose shape is inferred from the spec. The same spec is reused by the family interpreters and the language server (completion, go-to-definition, find-usages), replacing the per-attribute hand-written validation that is opaque to the editor today. Status: Proposed. Signed-off-by: Serhii Tatarintsev <[email protected]>
## What this is Slice 1 of 3 implementing [ADR 231 — Declarative attribute specifications](https://github.com/prisma/prisma-next/blob/main/docs/architecture%20docs/adrs/ADR%20231%20-%20Declarative%20attribute%20specifications.md), scoped to the **family interpreters**. It stands up the declarative-attribute engine in `psl-parser` and proves it end-to-end by migrating the SQL `@relation` attribute 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 declarative `AttributeSpec` per attribute, read by `interpretAttribute`, with the output type **inferred from the spec**. ## What's in this slice - **The engine + core types in `psl-parser`** — `ArgType`, `AttributeSpec`, `optional`/`fieldAttribute`, `interpretAttribute`, `InferAttr`, `InterpretCtx` — consuming the parser's `ExpressionAst` CST directly. - **The combinators `@relation` needs** — `str`, `enumOf`, `fieldRef(scope)`, `list({ nonEmpty, unique })`, plus a small `identifierName` leaf for bare-identifier enum values. - **SQL `@relation` migrated** to a declarative `sqlRelation` spec lowered through `interpretAttribute`; the hand-written `parseRelationAttribute` is deleted. ## Key decisions - **Combinators consume `ExpressionAst` directly** — no new intermediate argument representation. The CST already carries native literals and real spans. - **The kit lives in `psl-parser`**, which already owns `ExpressionAst` and the `SymbolTable`. No new package. - **Diagnostic-code parity via `InterpretCtx.diagnosticCode`** — the engine threads the spec's code (here `PSL_INVALID_RELATION_ATTRIBUTE`) to every leaf, so codes stay byte-identical. - **`onDelete`/`onUpdate` keep `normalizeReferentialAction` as validator** — they parse to the raw identifier name (no parse-time set check), preserving the existing `PSL_UNSUPPORTED_REFERENTIAL_ACTION` code + span. `enumOf` is intentionally not used for them. - **Parity bar (this project):** contract output and diagnostic **codes** are byte-identical; **spans** are no-coarser (the kit's per-argument anchoring narrows three `@relation` leaf spans — strictly more precise, exercised by no fixture); **messages** may adopt the kit's phrasing; malformed inputs legacy tolerated by coincidence (a quoted `onDelete: "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 `@relation` relations + diagnostics suites pass with **zero test edits**. - `pnpm fixtures:check` clean (no contract/migration drift); cross-package `pnpm typecheck` 143/143. Refs: TML-2956 · ADR 231 (#889). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added new PSL attribute-spec combinators (string, identifier, lists with `nonEmpty`/`unique`, optional values, and `oneOf` alternatives), plus field-level helpers and public exports to support authoring/interpretation. * Relation attribute parsing now uses these declarative attribute specs for consistent handling. * **Bug Fixes** * Improved span-aware, code-specific diagnostics for invalid, missing, and duplicate relation/attribute arguments. * Simplified referential action handling with clearer, unified error reporting. * **Tests** * Added/updated type-level and runtime test coverage for attribute combinators and relation interpretation. * **Documentation** * Updated the ADR to reflect `oneOf(identifier(...))` usage. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Serhii Tatarintsev <[email protected]>
Linked issue
n/a — no Linear issue. This PR adds a single design document (ADR 231) capturing a decision reached in discussion; it ships no code.
At a glance
The ADR proposes describing each PSL attribute once, as data. A relation:
is described by one declarative spec:
interpretAttribute(node, spec, ctx)turns a parsed AST node into a strongly-typed object whose shape is inferred from the spec — and the same spec is read by the language server for completion, go-to-definition, and find-usages.Decision
Add
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md(Status: Proposed). The ADR records a decision to replace per-attribute hand-written validation with a declarativeAttributeSpecper field/model/block attribute, composed from a fixed framework combinator kit:list/map/recordover native PSL literals;enumOffor fixed literal sets (string, numeric, or mixed);oneOfas an ordered, diagnostic-pure sum over alternative combinators;funcCall/funcCallFromthat reuse the same positional/named argument model;fieldRef(scope)/modelRef()/codecRef()reference combinators, wherescoperecords whether a field name resolves against our model or the referenced model.The motivating reason is reuse across consumers: attribute arguments are opaque to the language server today because their shape lives only as imperative interpreter code. One declarative description serves both the family interpreters and the editor.
How it fits together
The ADR follows the house format —
At a glance,Decision, numberedDesign principles, build-up sections (the combinator kit, positional/named model, type inference, resolution context, a dedicated language-server features section, cross-argument refinement, surface policy), an explicitOut of scopefor@db.*native types, thenConsequences,Alternatives considered,Open questions, andReferences.It was calibrated against two siblings: ADR 225 (three-layer extensibility for pack-contributed kinds — the contribution model the spec registry follows) and ADR 224 (control policy — the framework-vocabulary / family-dispatch split, and the
@@controlvalue set the spec types withenumOf).Reviewer notes
@default, index-element strictness, alias ergonomics, whether to fold generic-block parameters in, where collection-level invariants live). Status is deliberatelyProposedpending ratification.@db.*. The ADR explicitly excludes@db.*native types, because they attach to named-type declarations (type Slug = String @db.VarChar(191)), not to fields or models. This is stated as an out-of-scope section, not an omission.filter). This reflects a decision to drop the quoted-string form forinclude/exclude/weights, whose only current usage is in tests.examples/supabase,examples/mongo-blog-leaderboard).Testing performed
n/a — documentation only. Verified the four referenced ADRs (126, 221, 224, 225) and two pattern docs (
frozen-class-ast,three-layer-polymorphic-ir) resolve to existing files. There is no doc test suite to run.Skill update
n/a — adds an architecture decision record; no user-facing surface (CLI, public TypeScript API, config, error codes) changes.
Checklist
git commit -s) per the DCO.TML-NNNN: <sentence-case title>form — intentionally omitted; this ADR has no Linear issue.Alternatives considered
The ADR's own
Alternatives consideredsection weighs: keeping hand-written per-attribute validation; dispatchingoneOfwith a recognition predicate instead of ordered try-each; separateenumOf/numEnum; a codec-validatedjson(codecId); quoted-string surfaces for lists and maps; and monomorphic collection leaves. Each is recorded there with the reason it was not taken.Summary by CodeRabbit