TML-2956: migrate Mongo family attributes to declarative specs - #29833
TML-2956: migrate Mongo family attributes to declarative specs#29833StevenMcClankerton wants to merge 16 commits into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Plus Run ID: ⛔ Files ignored due to path filters (8)
📒 Files selected for processing (9)
🚧 Files skipped from review as they are similar to previous changes (8)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughAdds JSON and pinned-string PSL combinators. Migrates Mongo attribute interpretation from raw argument parsing to typed AST specifications with source-aware diagnostics for mappings, relations, polymorphism, and indexes. ChangesTyped PSL parser combinators
Mongo attribute interpretation
Estimated code review effort: 4 (Complex) | ~45 minutes Merge Risk: ⚪ Minimal · up to The PR is merge-ready after normal checks and review; no actionable merge-blocking risk remains. Suggested reviewers: Sequence Diagram(s)sequenceDiagram
participant PSLModel
participant AttributeSpecInterpreter
participant MongoInterpreter
participant Diagnostics
PSLModel->>AttributeSpecInterpreter: provide attribute AST nodes
AttributeSpecInterpreter->>MongoInterpreter: return typed attribute values
MongoInterpreter->>Diagnostics: append source-aware parse failures
MongoInterpreter->>PSLModel: produce mappings, relations, polymorphism, and indexes
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 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 |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts (1)
176-183: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value
indexFieldElementallocates onefuncCallarm per model field on every call.Each
buildIndexModelSpec/buildTextIndexModelSpecinvocation rebuilds the full arm list, andinterpreter.tscalls these inside the per-attribute loop, so a model with F fields and A index attributes builds F×A arms. Memoizing the element (or the spec pair) per model would keep it O(F).🤖 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-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts` around lines 176 - 183, The index field arm list is rebuilt for every attribute because indexFieldElement creates one funcCall per model field on each invocation. Memoize the resulting indexFieldElement or associated spec pair per model and reuse it across buildIndexModelSpec/buildTextIndexModelSpec calls, preserving the existing arms and behavior while reducing construction to O(F).packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts (1)
1581-1638: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRepeated find-then-assert block could be a helper.
The
find(d => d.code === 'PSL_INVALID_ATTRIBUTE_SYNTAX')+toBeDefined()+toMatch(/Expected one of/)triple appears four times here (and again in the polymorphism suite). A smallexpectSyntaxDiagnostic(result, /Expected one of/)helper would shrink each case to a line.🤖 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-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts` around lines 1581 - 1638, Extract the repeated syntax-diagnostic lookup and assertions into a shared expectSyntaxDiagnostic helper, using the existing result type and a message pattern parameter. Replace the duplicated find, toBeDefined, and toMatch blocks in these tests and the polymorphism suite with calls to the helper, preserving the PSL_INVALID_ATTRIBUTE_SYNTAX code and Expected one of checks.packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts (1)
552-565: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueA model field literally named
wildcardis misread as a wildcard element.
normalizeIndexFieldbranches onelement.fn === 'wildcard'before the sorted-field arm, so@@index([wildcard(sort: Desc)])on a model that declares a fieldwildcardyields{ name: '$**', isWildcard: true }instead of a descending key on that field. Narrow edge case, but a name check against the model's field names would disambiguate.🤖 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-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around lines 552 - 565, Update normalizeIndexField to distinguish the wildcard function from a model field named “wildcard” by checking the model’s declared field names before taking the wildcard branch. Preserve the wildcard scope handling for actual wildcard elements, while treating the field-name case as a sorted field and retaining its Desc direction.packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts (2)
87-125: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert the diagnostic code in every rejection case.
These tests only check that a failure exists for several invalid inputs, so they would pass even if the parser returned the wrong diagnostic. The PR contract requires
PSL_INVALID_ATTRIBUTE_SYNTAX; assert that code in each rejection branch.Suggested assertion
if (!result.ok) { expect(result.failure).toHaveLength(1); + expect(result.failure[0]?.code).toBe('PSL_INVALID_ATTRIBUTE_SYNTAX'); }Also applies to: 323-383
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts` around lines 87 - 125, Update the rejection branches in the tests around str('hashed'), including the additional cases at the referenced later range, to assert that the single failure has code PSL_INVALID_ATTRIBUTE_SYNTAX. Preserve the existing failure-length checks while adding the diagnostic-code assertion for every invalid input case.
87-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPlace the new
*.test.tscoverage alongside the source files.These additions remain in
test/, but the repository guideline requires*.test.tsfiles to be colocated with their source modules. Move this coverage beside the combinator implementation.As per coding guidelines, test files matching
*.test.tsshould be placed alongside source files.Also applies to: 323-383
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts` around lines 87 - 125, Move the new combinator coverage from the test directory to the source directory alongside the combinator implementation, preserving the existing filename pattern and all test cases. Apply the same relocation to the additional coverage referenced in the comment, and update any imports or test configuration references required by the move.Source: Coding guidelines
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts (1)
8-11: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse doc comments for both new exported combinators.
Both public APIs are described with ordinary
//headers instead of/** ... */documentation comments.
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts#L8-L11: convert thejson()header to JSDoc.packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts#L7-L10: convert thestr()header to JSDoc.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts` around lines 8 - 11, Convert the header comments immediately preceding the exported json() and str() combinators into JSDoc comments, preserving their existing descriptions and examples. Apply the change in packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts lines 8-11 and packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts lines 7-10.Source: Coding guidelines
🤖 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-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 136-181: Prevent repeated interpretation of malformed `@map` and
@@map attributes from appending duplicate diagnostics. Update
resolveFieldMappings and resolveCollectionName usage so each model’s field
mappings and collection name are computed once and reused across the main loop,
relation FK handling, collectPolymorphismDeclarations, and resolvePolymorphism,
or memoize those resolutions per model while preserving first-resolution
diagnostic emission.
---
Nitpick comments:
In
`@packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts`:
- Around line 8-11: Convert the header comments immediately preceding the
exported json() and str() combinators into JSDoc comments, preserving their
existing descriptions and examples. Apply the change in
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts
lines 8-11 and
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts
lines 7-10.
In
`@packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts`:
- Around line 87-125: Update the rejection branches in the tests around
str('hashed'), including the additional cases at the referenced later range, to
assert that the single failure has code PSL_INVALID_ATTRIBUTE_SYNTAX. Preserve
the existing failure-length checks while adding the diagnostic-code assertion
for every invalid input case.
- Around line 87-125: Move the new combinator coverage from the test directory
to the source directory alongside the combinator implementation, preserving the
existing filename pattern and all test cases. Apply the same relocation to the
additional coverage referenced in the comment, and update any imports or test
configuration references required by the move.
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 552-565: Update normalizeIndexField to distinguish the wildcard
function from a model field named “wildcard” by checking the model’s declared
field names before taking the wildcard branch. Preserve the wildcard scope
handling for actual wildcard elements, while treating the field-name case as a
sorted field and retaining its Desc direction.
In
`@packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts`:
- Around line 176-183: The index field arm list is rebuilt for every attribute
because indexFieldElement creates one funcCall per model field on each
invocation. Memoize the resulting indexFieldElement or associated spec pair per
model and reuse it across buildIndexModelSpec/buildTextIndexModelSpec calls,
preserving the existing arms and behavior while reducing construction to O(F).
In `@packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts`:
- Around line 1581-1638: Extract the repeated syntax-diagnostic lookup and
assertions into a shared expectSyntaxDiagnostic helper, using the existing
result type and a message pattern parameter. Replace the duplicated find,
toBeDefined, and toMatch blocks in these tests and the polymorphism suite with
calls to the helper, preserving the PSL_INVALID_ATTRIBUTE_SYNTAX code and
Expected one of checks.
🪄 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 Plus
Run ID: c1650314-8387-4fe3-93b8-6d89e77e18e2
⛔ Files ignored due to path filters (8)
projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/01-mongo-wiring-map.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/02-mongo-relation.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/03-mongo-polymorphism.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/04-kit-str-value-json.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/05-mongo-index.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/06-mongo-textindex-cleanup.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/mongo-attributes/plan.mdis excluded by!projects/**projects/typed-attribute-parsers/slices/mongo-attributes/spec.mdis excluded by!projects/**
📒 Files selected for processing (9)
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.tspackages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.tspackages/1-framework/2-authoring/psl-parser/src/exports/index.tspackages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.tspackages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts
| function resolveFieldMappings(input: { | ||
| readonly model: ModelSymbol; | ||
| readonly sourceFile: SourceFile; | ||
| readonly sourceId: string; | ||
| readonly diagnostics: ContractSourceDiagnostic[]; | ||
| }): FieldMappings { | ||
| const { model, sourceFile, sourceId, diagnostics } = input; | ||
| const pslNameToMapped = new Map<string, string>(); | ||
| for (const field of Object.values(model.fields)) { | ||
| const mapped = getMapName(field.attributes) ?? field.name; | ||
| const mapNode = findFieldAttributeNode(field, 'map'); | ||
| const mapped = | ||
| (mapNode | ||
| ? interpretFieldAttribute({ | ||
| node: mapNode, | ||
| spec: mapFieldSpec, | ||
| model, | ||
| field, | ||
| sourceFile, | ||
| sourceId, | ||
| diagnostics, | ||
| })?.name | ||
| : undefined) ?? field.name; | ||
| pslNameToMapped.set(field.name, mapped); | ||
| } | ||
| return { pslNameToMapped }; | ||
| } | ||
|
|
||
| function resolveCollectionName(model: ModelSymbol): string { | ||
| return getMapName(model.attributes) ?? lowerFirst(model.name); | ||
| function resolveCollectionName(input: { | ||
| readonly model: ModelSymbol; | ||
| readonly sourceFile: SourceFile; | ||
| readonly sourceId: string; | ||
| readonly diagnostics: ContractSourceDiagnostic[]; | ||
| }): string { | ||
| const { model, sourceFile, sourceId, diagnostics } = input; | ||
| const mapNode = findModelAttributeNode(model, 'map'); | ||
| const name = mapNode | ||
| ? interpretModelAttribute({ | ||
| node: mapNode, | ||
| spec: mapModelSpec, | ||
| model, | ||
| sourceFile, | ||
| sourceId, | ||
| diagnostics, | ||
| })?.name | ||
| : undefined; | ||
| return name ?? lowerFirst(model.name); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Repeated @map interpretation now duplicates diagnostics.
resolveFieldMappings/resolveCollectionName push parse failures into diagnostics on every call, and both are invoked several times for the same model: the main loop (Lines 1128-1139), the relation FK branch for target models (Line 1177), collectPolymorphismDeclarations (Line 258), and resolvePolymorphism (Lines 321, 414). A single malformed @map/@@map therefore emits the same diagnostic two or more times (the polymorphism copies land in a separate array that is concatenated at Line 1368). The old getMapName path was diagnostic-free, so this is new noise plus redundant re-interpretation.
Consider computing mappings/collection names once per model up front and threading the results, or memoizing by model with diagnostics emitted only on first resolution.
🤖 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-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around
lines 136 - 181, Prevent repeated interpretation of malformed `@map` and @@map
attributes from appending duplicate diagnostics. Update resolveFieldMappings and
resolveCollectionName usage so each model’s field mappings and collection name
are computed once and reused across the main loop, relation FK handling,
collectPolymorphismDeclarations, and resolvePolymorphism, or memoize those
resolutions per model while preserving first-resolution diagnostic emission.
…+ dispatch plan) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…@map/@@Map) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…attribute kit Land the Mongo-side wiring for the declarative attribute-spec kit by adding mongo-attribute-specs.ts (mirroring the SQL family, family-agnostic, no cross-family import) and migrating @map/@@Map end-to-end through interpretAttribute. - resolveFieldMappings/resolveCollectionName now take { model, sourceFile, sourceId, diagnostics } and interpret the map spec, draining failures into diagnostics. - Thread sourceFile/sourceId/diagnostics into all call sites, including collectPolymorphismDeclarations and resolvePolymorphism. - Variant presence check uses getAttribute instead of getMapName. - Delete the now-dead getMapName helper (getAttribute/stripQuotes retained). Behaviour is byte-identical for @map/@@Map; existing suite + fixtures:check are the primary signal. Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
@unique presence-only) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
… spec) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Replace the hand-written parseRelationAttribute string extraction with a declarative relationFieldSpec (name/fields/references, no refine) interpreted through interpretFieldAttribute, mirroring the SQL family. fieldRef adds field-existence validation the old parser lacked: a @relation naming a non-existent field now emits PSL_INVALID_ATTRIBUTE_SYNTAX. Valid schemas lower byte-identically. Retire parseRelationAttribute/ParsedRelationAttribute and the now-dead stripQuotes helper; keep parseFieldList. Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
@base to specs) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
… specs Replace the imperative getPositionalArgument/parseQuotedStringLiteral parsing in collectPolymorphismDeclarations with findModelAttributeNode + interpretModelAttribute against new discriminatorModelSpec/baseModelSpec, copied from the SQL templates. Argument-shape errors (missing arg, non-quoted value, non-existent discriminator field) now surface as grammar PSL_INVALID_ATTRIBUTE_SYNTAX; the discriminator-field-must-be- String check stays a semantic PSL_INVALID_ATTRIBUTE_ARGUMENT. resolvePolymorphism semantics are unchanged. getPositionalArgument and parseQuotedStringLiteral remain defined in psl-helpers for the index attributes. Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…mongo index surface) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Add two leaf combinators to the attribute-spec kit for the Mongo index
argument surface (wired in a later dispatch):
- str(value): a pinned string-literal overload of str(), mirroring
num()/num(value). Pins to a single literal (e.g. str("hashed")) for
digit-leading index type tokens that cannot be bare identifiers.
- json(): reads an opaque JSON object from a quoted, parser-decoded JSON
string, matching the interpreter parseJsonArg behaviour (non-array
object only). The single JSON.parse-of-unknown narrowing is a justified
blindCast; no bare as.
Both additions are additive: the unpinned str() and all existing
psl-parser/sql/mongo tests stay green with no edits. Adds focused unit
tests for both combinators.
Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
… to specs) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…o attribute specs Route model-level @@index and @@unique argument parsing through interpretModelAttribute + a new buildIndexModelSpec, replacing the imperative getNamedArgument/parse* helpers. The dense index-shape validation (PSL_INVALID_INDEX in all forms, the collation-locale-required rule), the PSL_INDEX_FIELD_NOT_FOUND existence check, key-building, and MongoIndex construction are unchanged; only the argument source moves onto specs. Lowering is byte-identical for valid schemas. buildIndexModelSpec composes a per-model field element (oneOf(fieldRef, wildcard(scope?), field(sort:))) plus the full named-arg surface (type/sparse/expireAfterSeconds/filter[json]/include/exclude[str]/ default_language/languageOverride + 9 collation args). @@textIndex stays on its existing pre-spec branch (migrated in a later dispatch). Per operator Option A, argument-shape errors now surface as PSL_INVALID_ATTRIBUTE_SYNTAX: a field reference absent from the model is rejected at the grammar layer by fieldRef, so PSL_INDEX_FIELD_NOT_FOUND now guards only present-but-not-indexable (relation) fields. parseIndexDirection is removed (its sole caller moved to the spec path; @@textIndex never used it). Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…delete legacy parsers) Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Add buildTextIndexModelSpec and route @@textIndex through the spec interpreter like @@index/@@unique, filling the same normalized locals via a cast-free two-branch (isTextIndex) structure since the two specs infer different named-arg shapes. Weights are number-filtered via a new extractWeights helper (typeof-narrowed, no cast). This orphans the pre-spec argument parsers, so delete them (biome noUnusedVariables): parseCollation, parseNumericArg, parseBooleanArg, parseJsonArg, stripQuotesHelper (interpreter.ts) and parseIndexFieldList, parseIndexFieldSegment, parseFieldList, splitTopLevel, getNamedArgument, getPositionalArgument (psl-helpers.ts). Keep parseProjectionList, getAttribute, lowerFirst, parseQuotedStringLiteral, ParsedIndexField. Reword the comments naming the removed parseIndexDirection/parseCollation. Per Option A, @@textIndex now rejects undeclared args and shifts undeclared-field references to PSL_INVALID_ATTRIBUTE_SYNTAX (via fieldRef); update the one shifted assertion. Contracts stay byte-identical for valid schemas. Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
The bare `as Contract['storage']` cast tripped scripts/lint-no-contract-cast.mjs, failing CI's Lint job. Replace it with blindCast<T, Reason>, an identity re-type, removing the as-Contract smell and one bare as. Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Signed-off-by: Steven McClankerton <tatarintsev@prisma.io>
e78cc55 to
e491496
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
@prisma/orm-extension-arktype-json
@prisma/orm-extension-middleware-cache
@prisma/orm-extension-paradedb
@prisma/orm-extension-pgvector
@prisma/orm-extension-postgis
@prisma/orm-extension-supabase
@prisma/orm-family-mongo
@prisma/orm-family-sql
@prisma/orm-framework
@prisma/orm-mongo
@prisma/orm-postgres
@prisma/orm-sqlite
@prisma/orm-target-mongo
@prisma/orm-target-postgres
@prisma/orm-target-sqlite
@prisma/orm-toolchain
commit: |
Linked issue
Refs TML-2956 — "Language Tools Support Prisma Next PSL" (the typed-attribute-parsers project's umbrella ticket).
Completes the family migrations begun in #932 (SQL non-
@defaultattributes) and #938 (SQL@default): this PR brings the Mongo family onto the same declarative attribute-spec kit. After it, every attribute in both families validates its arguments through the kit — no hand-written string parsers remain.At a glance
Every Mongo attribute is now described by an
AttributeSpecand lowered throughinterpretAttribute. The interesting one is the@@indexfield element —email,email(sort: Desc), andwildcard(tags)are all composed from existing combinators, built per model from its field names (the same dynamic-composition pattern@defaultuses over its function registry):Previously the Mongo interpreter parsed every attribute imperatively off a resolved
ResolvedAttributeview viapsl-helpers.tsstring scanners (parseIndexFieldList,parseRelationAttribute,parseCollation,getNamedArgument, …). All of that is gone.Decision
This PR makes the Mongo family fully spec-driven, mirroring the SQL family:
InterpretCtxwiring — a newmongo-attribute-specs.tsprovides the family-agnosticinterpretModelAttribute/interpretFieldAttributewrappers + ctx builders (a copy of the SQL shape, not a cross-family import).@map/@@map,@relation,@@discriminator/@@base,@@index/@@unique, and@@textIndexnow parse their arguments through specs.str(value)(pinned string literal, for the indextypeset) andjson()(the ADR's one text-encoded exception, forfilter/weights).sortedFieldRef/wildcardPathdissolve intofuncCallcomposition over the model's fields (ADR 231 principle 4, "compose don't special-case").How it fits together
@map/@@map).mongo-attribute-specs.tslands the ctx wiring, proven by migrating the simplest attribute — the mapped field/collection name — end-to-end.@relation(name alias +fields/referencesviafieldRef), then@@discriminator/@@base(field / model-name + value), each replacing a string scanner while leaving the cross-model semantics (backrelation matching, polymorphism consistency) untouched.str(value)andjson()are added topsl-parser— the only new combinators the whole slice needs.@@index/@@uniquethen@@textIndexmigrate to per-model specs (the dynamic field element + the full named-arg surface —type,sparse,expireAfterSeconds,filter,include/exclude,weights,language, and the 9 collation args). The dense index-shape validation stays in the interpreter, reading normalized values.Behavior changes & evidence
mongo-attribute-specs.ts(the specs + wiring) andinterpreter.ts(the migrated call sites); byte-identical contract output proven byinterpreter.test.ts+fixtures:check.PSL_INVALID_ATTRIBUTE_SYNTAX(rejected at parse byfieldRef, consistent with SQL@relation); a field that exists but isn't indexable (a relation field) → the semanticPSL_INDEX_FIELD_NOT_FOUND(downstream). Evidence ininterpreter.test.ts+interpreter.polymorphism.test.ts.str(value)pins a string literal;json()reads an opaque JSON object from a quoted string. Seestr.ts+json.ts; evidence inattribute-spec-combinators.test.ts.psl-helpers.tsshrinks from a bag of string scanners to a handful of survivors (getAttribute,lowerFirst,parseProjectionList,parseQuotedStringLiteral).Reviewer notes
sortedFieldRef/wildcardPathwere considered and dropped:field(sort: Desc)isfuncCall(field, { named: { sort } })andwildcard(scope)isfuncCall('wildcard', …), so the element isoneOfoverfieldRef+ the per-fieldfuncCallarms — pure composition, built dynamically per model.type, a non-boolsparse, invalidfilter/weightsJSON, a badsort) becomePSL_INVALID_ATTRIBUTE_SYNTAX;@@textIndexnow rejects args it doesn't accept (type/sparse/expireAfterSeconds) where the old path silently ignored them. AllPSL_INVALID_INDEXshape rules, the one-@@textIndex-per-collection guard, andPSL_INDEX_FIELD_NOT_FOUND(for relation fields) are preserved.oneOf, an absent-field reference surfaces as a genericExpected one of: …rather than naming the field — the same trade-off the SQL slices accepted. A futureoneOf-diagnostic enhancement could restore field-naming; out of scope here.@@indexon one model.findModelAttributeNodereturns the first same-named node, so the loop maps each resolved attribute to its AST node by position (node.attributes()order is 1:1 with the resolved list) — guarded by a new multi-index test.interpreter.ts(collectIndexes) — the index-shape validation andMongoIndexconstruction are byte-for-byte unchanged; only the argument source moved from string parsers to the spec output.projects/typed-attribute-parsers/slices/mongo-attributes/are included for review provenance (path-filtered out of automated review); they are migrated/removed at project close-out.Verification
Run on final HEAD:
pnpm --filter @prisma-next/mongo-contract-psl build && typecheck && test— clean; 155 testspnpm --filter @prisma-next/psl-parser build && typecheck && test— clean; 635 testspnpm --filter @prisma-next/sql-contract-psl test— 346 (unaffected by the additive kit changes)pnpm build— 68/68 ·pnpm fixtures:check— clean, no contract drift ·pnpm lint:deps— 0 ·pnpm lint:framework-vocabulary— 836/836parseIndexFieldList/parseRelationAttribute/parseCollation/getNamedArgument/…) — zero remaining incontract-psl/srcAlternatives considered
sortedFieldRef/wildcardPathcombinators. Rejected: with the model in context the field names are known, sooneOf(fieldRef, ...fields.map(funcCall), funcCall('wildcard'))composes the same grammar without new kit surface — the same reason@defaultdroppedfuncCallFrom.filter/weightsquoted JSON → object literals;include/excludequoted bracket-strings → native lists). Rejected: it would break existing Mongo schemas.json()preserves the quoted-JSON surface;include/excludestaystr()+parseProjectionList.PSL_INDEX_FIELD_NOT_FOUNDfor all field misses. Rejected:fieldRefvalidates existence at parse time, and the natural split (missing → syntax, relation-field-not-indexable → semantic) is both cleaner and consistent with how@relationalready behaves.Checklist
git commit -s) per the DCO.TML-NNNN: <sentence-case title>form.Summary by CodeRabbit
New Features
Bug Fixes