Repository navigation
feat(orm): add polymorphism authoring, types, and Mongo runtime via @@discriminator/@@base - #315
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 discriminator-based polymorphism across PSL parsing, SQL/Mongo contract generation, ORM client APIs/types (variant-aware reads/writes), example apps/CLI updates, and comprehensive tests and diagnostics for variant/base relationships. Changes
Sequence Diagram(s)sequenceDiagram
rect rgba(240,240,255,0.5)
participant Dev as Developer
participant PSL as PSL Interpreter
participant Contract as Contract Builder
participant ORM as ORM Client
participant DB as Database
end
Dev->>PSL: submit PSL with @@discriminator/@@base
PSL->>PSL: parse attributes, validate, collect diagnostics
alt valid
PSL->>Contract: inject discriminator, variants, base, adjust storage/roots
Dev->>ORM: call collection.variant('X').all() / create()
ORM->>ORM: add discriminator filter or inject discriminator into payload
ORM->>DB: execute query/insert with discriminator field/value
DB-->>ORM: return rows/documents
ORM-->>Dev: return typed variant-aware rows
else invalid
PSL-->>Dev: return diagnostics (fail)
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@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/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/runtime-executor
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-emitter
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-pipeline-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/adapter-postgres
@prisma-next/driver-postgres
commit: |
3e7c7a7 to
01e0631
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
examples/prisma-next-demo/src/main.ts (1)
310-322:⚠️ Potential issue | 🟡 MinorUsage string missing new commands.
The help text doesn't include
repo-tasks,repo-bugs, orrepo-features. Users won't discover these commands from the CLI help.Proposed fix
console.log( 'Usage: pnpm start -- [users [limit] | user <userId> | posts <userId> | ' + 'repo-users [limit] | repo-admins [limit] | ' + 'repo-user <email> | repo-posts <userId> [limit] | ' + 'repo-dashboard <emailDomain> <postTitleTerm> [limit] [postsPerUser] | ' + 'repo-post-feed <postTitleTerm> [limit] | repo-users-cursor [cursor] [limit] | ' + 'repo-latest-per-kind | repo-user-insights [limit] | repo-kind-breakdown [minUsers] | ' + + 'repo-tasks [limit] | repo-bugs [limit] | repo-features [limit] | ' + 'repo-upsert-user <id> <email> <kind> | repo-create-user-address <id> <email> <kind> | ' + 'users-paginate [cursor] [limit] | ' + 'users-paginate-back <cursor> [limit] | similarity-search <vec> [limit] | ' + 'budget-violation | guardrail-delete]', );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/src/main.ts` around lines 310 - 322, The CLI usage string printed in the else branch (the large console.log starting with 'Usage: pnpm start -- [users ...') is missing the new commands repo-tasks, repo-bugs, and repo-features; update that usage text (in main.ts where the 'Usage:' console.log is emitted) to include those three commands in the appropriate section(s) so the help output lists repo-tasks, repo-bugs, and repo-features alongside the other repo-* commands.packages/3-extensions/sql-orm-client/src/orm.ts (1)
59-63:⚠️ Potential issue | 🟠 MajorBuild the top-level ORM surface from
contract.roots, notcontract.models.
interpretPslDocumentToSqlContract()now removes variant models fromcontract.roots, but this proxy still enumerates and validates against the fullcontract.modelsset. That keepsorm.Bug/orm.Featurepublicly reachable even though the PR makes variants non-roots, and it bypasses the new root boundary entirely. Filter bothmodelNamesand custom-collection registration to roots (or models withoutbase) instead.Also applies to: 119-135
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/src/orm.ts` around lines 59 - 63, The code currently builds modelNames and registers custom collections from contract.models, exposing variant models that are no longer roots; update the logic to derive public models from contract.roots (or equivalently from contract.models entries where model.base is undefined) so the ORM surface only includes root models: change the Set creation for modelNames to iterate contract.roots (or filter Object.keys(contract.models) by model.base === undefined) and ensure createCollectionRegistry is called with that filtered set (or only register collections whose modelName is in the roots set); apply the same root-filtering approach to the other registration block referenced by the earlier section (the block around the custom-collection registration later in the file) so both modelNames and custom collections respect the root boundary.
🧹 Nitpick comments (4)
examples/prisma-next-demo/test/demo-dx.integration.test.ts (1)
56-60: Use a single object matcher for related shape checks.These are related assertions on the same object; consolidate them with
toMatchObjectfor clearer intent and guideline compliance.♻️ Suggested refactor
- const m = model as Record<string, unknown>; - expect(m['storage']).toBeDefined(); - expect(m['fields']).toBeDefined(); - expect(m['relations']).toBeDefined(); - expect(typeof m['relations']).toBe('object'); + const m = model as Record<string, unknown>; + expect(m).toMatchObject({ + storage: expect.any(Object), + fields: expect.any(Object), + relations: expect.any(Object), + });As per coding guidelines,
**/*.test.ts: “Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests”.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo/test/demo-dx.integration.test.ts` around lines 56 - 60, Consolidate the multiple related assertions on the test variable m into a single object matcher: replace the separate expect(m['storage']).toBeDefined(), expect(m['fields']).toBeDefined(), expect(m['relations']).toBeDefined(), and expect(typeof m['relations']).toBe('object') with one expect(m).toMatchObject(...) call that asserts the presence of keys 'storage' and 'fields' (e.g., using expect.anything() or a defined matcher) and that 'relations' is an object (e.g., expect.any(Object)); update the test around the model -> m usage to use this single matcher.packages/2-mongo-family/5-query-builders/orm/test/collection.test.ts (1)
146-228: Split the new variant suite into its own test file.
collection.test.tsis already well past the repo's 500-line limit, and adding the polymorphism cases here makes it even harder to navigate. Moving this block to something likecollection.variant.test.tsorcollection.polymorphism.test.tswould keep the unit suites searchable and easier to maintain.As per coding guidelines, "Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/5-query-builders/orm/test/collection.test.ts` around lines 146 - 228, Move the entire "MongoCollection variant()" test suite (the describe block that uses createMongoCollection, col.variant, and tests like "injects discriminator eq filter", "create() injects discriminator value", "createAll() injects discriminator value") out of collection.test.ts into a new test file (suggestion: collection.variant.test.ts or collection.polymorphism.test.ts); ensure you export/import nothing — the new file should import the same test helpers (createMongoCollection, createMockExecutor, MongoFieldFilter, etc.) and keep the tests unchanged so the suite remains isolated and the original collection.test.ts drops below 500 lines.packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts (1)
384-386: Type mutation pattern for adding polymorphism metadata.The casts to
Record<string, unknown>are necessary here sinceMutableDomainModeldoesn't declarediscriminatororvariantsproperties. Consider whether extendingMutableDomainModelwith optional discriminator/variants/base properties would improve type safety and eliminate these casts.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around lines 384 - 386, The code mutates models[modelName] to add polymorphism metadata by setting (models[modelName] as Record<string, unknown>)['discriminator'] and ['variants'], which forces unsafe casts; update the type instead: extend the MutableDomainModel interface (or create an intersection type) to include optional properties discriminator?: { field: string } and variants?: /* appropriate type */ (and optional base?: string if used), then remove the ad-hoc casts and assign directly to models[modelName].discriminator and .variants so the compiler enforces the shape without Record<string, unknown> hacks.packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts (1)
14-506: Split this suite before it grows further.This file is already over the repo's 500-line limit and contains three distinct concerns (
happy paths,diagnostics,end-to-end). Breaking it into separate*.happy-path.test.ts/*.diagnostics.test.tsfiles will keep failures easier to scan.As per coding guidelines, "Keep test files under 500 lines... Split test files when they exceed 500 lines, contain multiple distinct concerns that can be logically separated, or have multiple top-level describe blocks that can be split by functionality."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts` around lines 14 - 506, The test file contains three distinct concerns and should be split: extract the " @@discriminator and @@base — happy paths", " @@discriminator and @@base — diagnostics", and "end-to-end: PSL → interpret → domain validation" describe blocks into three separate test files; each new file should re-use the existing setup (the builtinControlMutationDefaults created via createBuiltinLikeControlMutationDefaults and the wrapper interpretPslDocumentToSqlContract that calls interpretPslDocumentToSqlContractInternal with postgresTarget/postgresScalarTypeDescriptors) and import any helpers like parsePslDocument and validateContractDomain so tests remain identical, then remove the moved describe block from the original file to bring each file under 500 lines.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@examples/prisma-next-demo/src/orm-client/get-tasks.ts`:
- Around line 4-16: The demo helper functions expose variant-specific reads that
the SQL runtime doesn't yet support; update or remove the variant helpers so
they only return base Task fields. Specifically, change ormClientGetBugs and
ormClientGetFeatures (and/or the call sites that use them) to use the root Task
read like ormClientGetTasks (e.g., use db.Task.take(limit).all() or an
equivalent root-only query via createOrmClient) so no variant-only fields are
requested until polymorphic SQL reads are implemented. Ensure the returned types
and any consumers expect only base Task fields.
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 384-385: The code allows own-table variants (detected via
isVariantModel from model.attributes and the storage.table rewrite via
@@base/@@map) to pass the primary-key check because primaryKeyColumns can be
empty; fix by either rejecting own-table variants when isVariantModel is true
and primaryKeyColumns.length === 0 (throw a clear validation error referencing
@@base/@@map and storage.table) or by emitting the base-key metadata so the
runtime can map variant rows back to the base (add base key/foreign-key fields
into the model output and populate a baseKeyColumns / baseKeyMapping alongside
primaryKeyColumns so later planner code can join/hydrate variants); apply the
same change to the other affected block around the second occurrence (lines
~949-960) to ensure consistent behavior.
- Around line 832-842: The branch that accepts the quoted discriminator value
(uses parseQuotedStringLiteral and then baseDeclarations.set) must also verify
the referenced discriminator field's scalar type is actually a string; update
the logic where you parse the quoted literal (and the similar block around the
other discriminator handling at 875-883) to look up the field on model (using
model.fields / the same field resolution you already use), confirm its type is a
string scalar (not Int or other), and if not push a
PSL_INVALID_ATTRIBUTE_ARGUMENT diagnostic with a clear message and continue
instead of calling baseDeclarations.set; reference the existing symbols
parseQuotedStringLiteral, diagnostics.push, attr/span, model.name, and
baseDeclarations.set when making the change.
In `@packages/3-extensions/sql-orm-client/src/collection.ts`:
- Around line 232-251: The variant() call currently appends a new discriminator
filter causing contradictory ANDs; modify variant() in Collection so it first
checks this.state.variantName and/or scans this.state.filters for an existing
discriminator BinaryExpr (use resolveFieldToColumn(this.contract,
this.modelName, discriminator.field) to identify the column) and then either (a)
if an identical variant is requested, return the current instance unchanged, (b)
if a different variant is present, replace the existing discriminator filter
with the new BinaryExpr (i.e., remove the old filter from filters before calling
`#cloneWithRow`) or (c) alternatively throw a clear error when attempting to set a
conflicting variant; ensure state.variantName is updated consistently when
replacing the filter and that you use the same filter construction
(BinaryExpr.eq with ColumnRef.of and LiteralExpr.of) so behavior remains
consistent.
---
Outside diff comments:
In `@examples/prisma-next-demo/src/main.ts`:
- Around line 310-322: The CLI usage string printed in the else branch (the
large console.log starting with 'Usage: pnpm start -- [users ...') is missing
the new commands repo-tasks, repo-bugs, and repo-features; update that usage
text (in main.ts where the 'Usage:' console.log is emitted) to include those
three commands in the appropriate section(s) so the help output lists
repo-tasks, repo-bugs, and repo-features alongside the other repo-* commands.
In `@packages/3-extensions/sql-orm-client/src/orm.ts`:
- Around line 59-63: The code currently builds modelNames and registers custom
collections from contract.models, exposing variant models that are no longer
roots; update the logic to derive public models from contract.roots (or
equivalently from contract.models entries where model.base is undefined) so the
ORM surface only includes root models: change the Set creation for modelNames to
iterate contract.roots (or filter Object.keys(contract.models) by model.base ===
undefined) and ensure createCollectionRegistry is called with that filtered set
(or only register collections whose modelName is in the roots set); apply the
same root-filtering approach to the other registration block referenced by the
earlier section (the block around the custom-collection registration later in
the file) so both modelNames and custom collections respect the root boundary.
---
Nitpick comments:
In `@examples/prisma-next-demo/test/demo-dx.integration.test.ts`:
- Around line 56-60: Consolidate the multiple related assertions on the test
variable m into a single object matcher: replace the separate
expect(m['storage']).toBeDefined(), expect(m['fields']).toBeDefined(),
expect(m['relations']).toBeDefined(), and expect(typeof
m['relations']).toBe('object') with one expect(m).toMatchObject(...) call that
asserts the presence of keys 'storage' and 'fields' (e.g., using
expect.anything() or a defined matcher) and that 'relations' is an object (e.g.,
expect.any(Object)); update the test around the model -> m usage to use this
single matcher.
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 384-386: The code mutates models[modelName] to add polymorphism
metadata by setting (models[modelName] as Record<string,
unknown>)['discriminator'] and ['variants'], which forces unsafe casts; update
the type instead: extend the MutableDomainModel interface (or create an
intersection type) to include optional properties discriminator?: { field:
string } and variants?: /* appropriate type */ (and optional base?: string if
used), then remove the ad-hoc casts and assign directly to
models[modelName].discriminator and .variants so the compiler enforces the shape
without Record<string, unknown> hacks.
In `@packages/2-mongo-family/5-query-builders/orm/test/collection.test.ts`:
- Around line 146-228: Move the entire "MongoCollection variant()" test suite
(the describe block that uses createMongoCollection, col.variant, and tests like
"injects discriminator eq filter", "create() injects discriminator value",
"createAll() injects discriminator value") out of collection.test.ts into a new
test file (suggestion: collection.variant.test.ts or
collection.polymorphism.test.ts); ensure you export/import nothing — the new
file should import the same test helpers (createMongoCollection,
createMockExecutor, MongoFieldFilter, etc.) and keep the tests unchanged so the
suite remains isolated and the original collection.test.ts drops below 500
lines.
In
`@packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts`:
- Around line 14-506: The test file contains three distinct concerns and should
be split: extract the " @@discriminator and @@base — happy paths", "
@@discriminator and @@base — diagnostics", and "end-to-end: PSL → interpret →
domain validation" describe blocks into three separate test files; each new file
should re-use the existing setup (the builtinControlMutationDefaults created via
createBuiltinLikeControlMutationDefaults and the wrapper
interpretPslDocumentToSqlContract that calls
interpretPslDocumentToSqlContractInternal with
postgresTarget/postgresScalarTypeDescriptors) and import any helpers like
parsePslDocument and validateContractDomain so tests remain identical, then
remove the moved describe block from the original file to bring each file under
500 lines.
🪄 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: e150f5c0-40fc-4316-9787-e7560aec2e15
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/orm-consolidation/plans/phase-1.75b-polymorphism-plan.mdis excluded by!projects/**projects/orm-consolidation/specs/polymorphism.spec.mdis excluded by!projects/**
📒 Files selected for processing (30)
examples/mongo-demo/prisma/contract.prismaexamples/mongo-demo/src/contract.d.tsexamples/mongo-demo/src/contract.jsonexamples/mongo-demo/src/server.tsexamples/mongo-demo/test/blog.test.tsexamples/prisma-next-demo/prisma/schema.prismaexamples/prisma-next-demo/src/main.tsexamples/prisma-next-demo/src/orm-client/client.tsexamples/prisma-next-demo/src/orm-client/collections.tsexamples/prisma-next-demo/src/orm-client/get-tasks.tsexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/test/demo-dx.integration.test.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.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/5-query-builders/orm/package.jsonpackages/2-mongo-family/5-query-builders/orm/src/collection.tspackages/2-mongo-family/5-query-builders/orm/src/exports/index.tspackages/2-mongo-family/5-query-builders/orm/src/types.tspackages/2-mongo-family/5-query-builders/orm/test/collection.test.tspackages/2-mongo-family/5-query-builders/orm/test/integration/polymorphism.test.tspackages/2-mongo-family/5-query-builders/orm/test/orm-types.test-d.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/orm.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (2)
384-385:⚠️ Potential issue | 🔴 CriticalOwn-table variants still have no contract-level link back to the base row.
Skipping the PK requirement for
@@basemodels and then only rewritingstorage.tablelets@@base(...)+@@map(...)emit standalone variant tables with no primary key or FK to the base model. The generated demo contract already hasbug/featuretables with only variant-local columns, so aTaskvariant row cannot be uniquely identified or hydrated from the contract. Safest short-term fix is to reject explicit@@mapon SQL variants until base-key metadata is emitted.Also applies to: 949-960
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 384 - 385, The code currently skips the primary-key requirement for models with a 'base' attribute (isVariantModel) and only rewrites storage.table, which allows explicit @@map on SQL variants to produce standalone tables without PK/FK back to the base; change the validation to reject explicit @@map on variant models until base-key metadata is emitted: inside the same check that computes isVariantModel (using model.attributes.some(...)) add a guard that detects an explicit table mapping (storage.table or model-level @@map) and throw a clear validation error when isVariantModel && explicit map is present, referencing isVariantModel, primaryKeyColumns, and storage.table so the code prevents emitting unmapped variant tables.
832-842:⚠️ Potential issue | 🟠 MajorReject non-string discriminator fields.
You parse
@@base(..., "bug")values as strings, but this validation only checks that the referenced discriminator field exists. AnInt, JSON, or value-object field will still pass here even though downstreamvariants[].valuemetadata and SQLvariant()filters are string-based. Validate that the resolved field is a scalar string type before accepting the declaration.Also applies to: 875-883
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 832 - 842, The code accepts @@base(..., "val") without verifying the referenced discriminator field's type; update the validation in the parse/attribute handling around parseQuotedStringLiteral and where baseDeclarations is set to also resolve the referenced field on the model and confirm it's a scalar string (e.g., type === 'String' or equivalent scalar-string check) before pushing baseDeclarations; if the field is missing or not a string, push a PSL_INVALID_ATTRIBUTE_ARGUMENT diagnostic (similar to the existing diagnostics object) and skip adding to baseDeclarations. Apply the same string-type validation to the other block handling base declarations at the second location (the 875–883 area) so both code paths reject non-string discriminator fields.
🧹 Nitpick comments (1)
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts (1)
368-386: Consider validating duplicate discriminator values.The code collects variants and their discriminator values but doesn't check for duplicates. If two variant models declare the same discriminator value (e.g.,
@@base(Post, "article")on bothArticleandVideo), both would be stored invariantswithout error, but only one would survive since they'd have the same key. However, the issue is if two different variants map to the samevaluestring—this could cause runtime ambiguity.♻️ Proposed validation for duplicate discriminator values
const variants: Record<string, { readonly value: string }> = {}; + const seenValues = new Set<string>(); for (const [variantName, baseDecl] of baseDeclarations) { if (baseDecl.baseName !== modelName) continue; + if (seenValues.has(baseDecl.value)) { + polyDiagnostics.push({ + code: 'PSL_DUPLICATE_DISCRIMINATOR_VALUE', + message: `Discriminator value "${baseDecl.value}" is used by multiple variants of "${modelName}"`, + sourceId, + span: baseDecl.span, + }); + continue; + } + seenValues.add(baseDecl.value); variants[variantName] = { value: baseDecl.value }; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around lines 368 - 386, The variants collection loop (using baseDeclarations, variantName, baseDecl, and variants) currently doesn't detect when two different variant models declare the same discriminator value; add a validation after building variants to detect duplicate baseDecl.value strings (e.g., map value->firstVariant and if a different variantName uses the same value) and when found push a diagnostic (e.g., code 'PSL_DUPLICATE_DISCRIMINATOR') into polyDiagnostics with a message referencing modelName, the duplicated value and both variant names and include decl.span/sourceId; decide whether to skip the later duplicate or keep the first but ensure the diagnostics are emitted before assigning models[modelName].discriminator and .variants.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/2-mongo-family/5-query-builders/orm/src/types.ts`:
- Around line 101-127: The package's public API is missing the exported
VariantNames type used by MongoCollection.variant<V extends VariantNames<...>>;
add VariantNames to the public exports file alongside VariantCreateInput so
consumers can reference it. Locate the exports declaration that already
re-exports VariantCreateInput and include VariantNames in the same export list
(the type declared as VariantNames in types.ts) so the symbol is exported from
the package root for external use.
In `@packages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts`:
- Line 179: Replace direct single casts to TaskRow with an explicit unknown
boundary: wherever the test uses "{} as TaskRow" (e.g., the variable r and the
other mock on the same test), change them to "{} as unknown as TaskRow" so the
unsafe cast is explicit per test conventions; update both occurrences that
currently use the single cast.
---
Duplicate comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 384-385: The code currently skips the primary-key requirement for
models with a 'base' attribute (isVariantModel) and only rewrites storage.table,
which allows explicit @@map on SQL variants to produce standalone tables without
PK/FK back to the base; change the validation to reject explicit @@map on
variant models until base-key metadata is emitted: inside the same check that
computes isVariantModel (using model.attributes.some(...)) add a guard that
detects an explicit table mapping (storage.table or model-level @@map) and throw
a clear validation error when isVariantModel && explicit map is present,
referencing isVariantModel, primaryKeyColumns, and storage.table so the code
prevents emitting unmapped variant tables.
- Around line 832-842: The code accepts @@base(..., "val") without verifying the
referenced discriminator field's type; update the validation in the
parse/attribute handling around parseQuotedStringLiteral and where
baseDeclarations is set to also resolve the referenced field on the model and
confirm it's a scalar string (e.g., type === 'String' or equivalent
scalar-string check) before pushing baseDeclarations; if the field is missing or
not a string, push a PSL_INVALID_ATTRIBUTE_ARGUMENT diagnostic (similar to the
existing diagnostics object) and skip adding to baseDeclarations. Apply the same
string-type validation to the other block handling base declarations at the
second location (the 875–883 area) so both code paths reject non-string
discriminator fields.
---
Nitpick comments:
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 368-386: The variants collection loop (using baseDeclarations,
variantName, baseDecl, and variants) currently doesn't detect when two different
variant models declare the same discriminator value; add a validation after
building variants to detect duplicate baseDecl.value strings (e.g., map
value->firstVariant and if a different variantName uses the same value) and when
found push a diagnostic (e.g., code 'PSL_DUPLICATE_DISCRIMINATOR') into
polyDiagnostics with a message referencing modelName, the duplicated value and
both variant names and include decl.span/sourceId; decide whether to skip the
later duplicate or keep the first but ensure the diagnostics are emitted before
assigning models[modelName].discriminator and .variants.
🪄 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: a4616463-a721-4289-bb41-84992bb6d4c8
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/orm-consolidation/plans/phase-1.75b-polymorphism-plan.mdis excluded by!projects/**projects/orm-consolidation/specs/polymorphism.spec.mdis excluded by!projects/**
📒 Files selected for processing (30)
examples/mongo-demo/prisma/contract.prismaexamples/mongo-demo/src/contract.d.tsexamples/mongo-demo/src/contract.jsonexamples/mongo-demo/src/server.tsexamples/mongo-demo/test/blog.test.tsexamples/prisma-next-demo/prisma/schema.prismaexamples/prisma-next-demo/src/main.tsexamples/prisma-next-demo/src/orm-client/client.tsexamples/prisma-next-demo/src/orm-client/collections.tsexamples/prisma-next-demo/src/orm-client/get-tasks.tsexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/test/demo-dx.integration.test.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.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/5-query-builders/orm/package.jsonpackages/2-mongo-family/5-query-builders/orm/src/collection.tspackages/2-mongo-family/5-query-builders/orm/src/exports/index.tspackages/2-mongo-family/5-query-builders/orm/src/types.tspackages/2-mongo-family/5-query-builders/orm/test/collection.test.tspackages/2-mongo-family/5-query-builders/orm/test/integration/polymorphism.test.tspackages/2-mongo-family/5-query-builders/orm/test/orm-types.test-d.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/orm.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts
✅ Files skipped from review due to trivial changes (8)
- packages/2-mongo-family/5-query-builders/orm/src/exports/index.ts
- packages/2-mongo-family/5-query-builders/orm/package.json
- packages/3-extensions/sql-orm-client/src/orm.ts
- examples/prisma-next-demo/src/orm-client/collections.ts
- examples/prisma-next-demo/src/orm-client/get-tasks.ts
- packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
- packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
- packages/3-extensions/sql-orm-client/src/types.ts
🚧 Files skipped from review as they are similar to previous changes (9)
- examples/prisma-next-demo/test/demo-dx.integration.test.ts
- examples/prisma-next-demo/src/main.ts
- packages/2-sql/3-tooling/emitter/src/index.ts
- examples/mongo-demo/test/blog.test.ts
- packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
- packages/2-mongo-family/5-query-builders/orm/test/integration/polymorphism.test.ts
- packages/2-mongo-family/5-query-builders/orm/test/collection.test.ts
- packages/3-extensions/sql-orm-client/src/collection.ts
- packages/2-mongo-family/5-query-builders/orm/src/collection.ts
01e0631 to
78d9147
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/2-mongo-family/5-query-builders/orm/src/collection.ts (1)
45-54:⚠️ Potential issue | 🟠 Major
variant()doesn't narrow collection results yet.
TVariantis threaded into write inputs viaResolvedCreateInput<..., TVariant>, but every read/mutation return type still usesIncludedRow<TContract, ModelName, TIncludes>, which doesn't accept a variant parameter and returns the full root union instead of the narrowed variant. TheVariantModelRow<TContract, ModelName, V>helper exists but is never used in the collection surface. UpdateIncludedRowto acceptTVariantand narrow results consistently across.first(),.all(),.create(),.update(),.delete(), and.upsert().🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts` around lines 45 - 54, The collection's variant narrowing isn't applied to read/mutation return types: thread TVariant into IncludedRow and use VariantModelRow to narrow results. Update the IncludedRow type to accept TVariant and internally resolve to VariantModelRow<TContract, ModelName, TVariant> so that MongoCollection<TContract, ModelName, TIncludes, TVariant> methods (.first, .all, .create, .update, .delete, .upsert) return rows narrowed by TVariant; keep ResolvedCreateInput<..., TVariant> for writes but change all read/mutation return types from IncludedRow<TContract, ModelName, TIncludes> to IncludedRow<TContract, ModelName, TIncludes, TVariant> (and adjust any helper signatures that reference IncludedRow).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts`:
- Around line 143-164: variant() currently appends the discriminator predicate
into `#state.filters` and uses blind "as unknown as" casts, which breaks
mutation-safety and stacking of variants; change variant<V>() to only record the
chosen variant in the instance state (set `#variantName` via `#clone` without
pushing a discriminator filter into `#state.filters`), and ensure discriminator
filters are injected later when building/compiling filters (e.g., wherever
filters are compiled for queries/updates/delete so `#requireFilters`() still
requires explicit .where()); replace the unsafe fallback casts by introducing a
type-narrowing check or type predicate (e.g., an isValidVariant(model,
variantName) predicate or refine the return type) so that when
model?.discriminator or model.variants is missing you return the properly typed
this without using "as unknown as", and keep use of MongoFieldFilter.eq /
MongoParamRef only in the filter-compilation path instead of here.
In `@packages/2-mongo-family/5-query-builders/orm/src/types.ts`:
- Around line 217-223: ResolvedCreateInput currently falls back to CreateInput
when TVariant is never, allowing callers to omit the discriminator for
polymorphic models; update ResolvedCreateInput to detect if the target model
(TContract['models'][ModelName]) defines a discriminator and, if so, do NOT
return the non-variant CreateInput fallback—require either an explicit
discriminator in the input or a union of VariantCreateInput for all variants;
specifically change the conditional in ResolvedCreateInput so it checks the
model's discriminator presence (e.g., via a type like
TContract['models'][ModelName] extends { discriminator?: infer D } ) and return
VariantCreateInput<ModelName, TVariant> or a union of all variant inputs when a
discriminator exists, leaving the original CreateInput only for non-polymorphic
models, and ensure this aligns with the runtime `#injectDiscriminator` behavior.
---
Outside diff comments:
In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts`:
- Around line 45-54: The collection's variant narrowing isn't applied to
read/mutation return types: thread TVariant into IncludedRow and use
VariantModelRow to narrow results. Update the IncludedRow type to accept
TVariant and internally resolve to VariantModelRow<TContract, ModelName,
TVariant> so that MongoCollection<TContract, ModelName, TIncludes, TVariant>
methods (.first, .all, .create, .update, .delete, .upsert) return rows narrowed
by TVariant; keep ResolvedCreateInput<..., TVariant> for writes but change all
read/mutation return types from IncludedRow<TContract, ModelName, TIncludes> to
IncludedRow<TContract, ModelName, TIncludes, TVariant> (and adjust any helper
signatures that reference IncludedRow).
🪄 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: 7615131f-dff6-42ca-bcef-5163c3473e65
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/orm-consolidation/plans/phase-1.75b-polymorphism-plan.mdis excluded by!projects/**projects/orm-consolidation/specs/polymorphism.spec.mdis excluded by!projects/**
📒 Files selected for processing (30)
examples/mongo-demo/prisma/contract.prismaexamples/mongo-demo/src/contract.d.tsexamples/mongo-demo/src/contract.jsonexamples/mongo-demo/src/server.tsexamples/mongo-demo/test/blog.test.tsexamples/prisma-next-demo/prisma/schema.prismaexamples/prisma-next-demo/src/main.tsexamples/prisma-next-demo/src/orm-client/client.tsexamples/prisma-next-demo/src/orm-client/collections.tsexamples/prisma-next-demo/src/orm-client/get-tasks.tsexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/test/demo-dx.integration.test.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.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/5-query-builders/orm/package.jsonpackages/2-mongo-family/5-query-builders/orm/src/collection.tspackages/2-mongo-family/5-query-builders/orm/src/exports/index.tspackages/2-mongo-family/5-query-builders/orm/src/types.tspackages/2-mongo-family/5-query-builders/orm/test/collection.test.tspackages/2-mongo-family/5-query-builders/orm/test/integration/polymorphism.test.tspackages/2-mongo-family/5-query-builders/orm/test/orm-types.test-d.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/orm.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts
✅ Files skipped from review due to trivial changes (10)
- packages/2-mongo-family/5-query-builders/orm/package.json
- packages/2-mongo-family/5-query-builders/orm/src/exports/index.ts
- packages/3-extensions/sql-orm-client/src/orm.ts
- examples/prisma-next-demo/src/orm-client/collections.ts
- packages/2-mongo-family/5-query-builders/orm/test/collection.test.ts
- packages/2-mongo-family/5-query-builders/orm/test/integration/polymorphism.test.ts
- packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
- packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
- packages/3-extensions/sql-orm-client/src/collection.ts
- examples/prisma-next-demo/src/prisma/contract.d.ts
🚧 Files skipped from review as they are similar to previous changes (12)
- examples/prisma-next-demo/src/orm-client/client.ts
- examples/mongo-demo/prisma/contract.prisma
- examples/mongo-demo/test/blog.test.ts
- examples/prisma-next-demo/test/demo-dx.integration.test.ts
- examples/prisma-next-demo/src/orm-client/get-tasks.ts
- packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
- examples/prisma-next-demo/src/main.ts
- packages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts
- packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
- examples/mongo-demo/src/contract.d.ts
- packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
- packages/3-extensions/sql-orm-client/src/types.ts
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/2-mongo-family/5-query-builders/orm/src/collection.ts (2)
398-423:⚠️ Potential issue | 🟠 Major
upsert.updatecan defeat the active variant on insert.
#injectDiscriminator()only normalizesinput.create, but#toSetFields()still accepts the discriminator field. Because$setwins over$setOnInsert,collection.variant('Bug').upsert(...)can insert a non-Bugdocument on the no-match path. This guard probably belongs in the shared update normalization soupdate*()cannot rewrite the selected variant either.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts` around lines 398 - 423, The upsert path lets update fields overwrite the selected variant because `#injectDiscriminator` is only applied to input.create while `#toSetFields`(input.update) can include the discriminator; change the update normalization so the discriminator cannot be set: either have the shared update normalization (the function that `#toSetFields` calls) strip/reject the discriminator key or have upsert explicitly remove the discriminator from setFields (and/or call `#injectDiscriminator` on the update-normalizer) before building updateDoc; update the code paths using `#toSetFields` (including upsert and other update* methods) so they consistently refuse or ignore writes to the model discriminator (use the internal discriminator identifier used elsewhere in the class such as the discriminator field constant/member).
45-114:⚠️ Potential issue | 🟠 MajorThread
TVariantinto result types usingVariantModelRow.The
TVariantgeneric inMongoCollectioncorrectly narrows write inputs viaResolvedCreateInput<..., TVariant>, but all result-returning methods (first(),all(),create(),createAll(),upsert()) returnIncludedRow<TContract, ModelName, TIncludes>without usingTVariant. This means.variant('Bug').first()still surfaces the root-row union instead of the Bug-specific variant row.The infrastructure exists:
VariantModelRow<TContract, ModelName, VariantName>can narrow to a specific variant. UpdateIncludedRowor introduce a variant-aware result type that usesTVariantwhen it's notnever.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts` around lines 45 - 114, The collection's TVariant is applied to inputs but not to outputs—methods first(), all(), create(), createAll(), and upsert() return IncludedRow<TContract,ModelName,TIncludes> instead of a variant-narrowed row; update the return types to thread TVariant through by using VariantModelRow<TContract,ModelName,TVariant> (or a small helper type that resolves to DefaultModelRow/VariantModelRow when TVariant is never) and wrap that in IncludedRow<TContract,ModelName,TIncludes, /* variant-aware row */>; change signatures on first(), all(), create(), createAll(), and upsert() to use this variant-aware result type so .variant('X').first() yields the narrowed variant row.
♻️ Duplicate comments (1)
packages/2-mongo-family/5-query-builders/orm/src/collection.ts (1)
143-166:⚠️ Potential issue | 🔴 CriticalStill keep variant selection out of
#state.filters.
variant()still appends the discriminator predicate into#state.filters. That lets.variant(...).update/delete/upsert()satisfy#requireFilters()without any explicit.where(), and a secondvariant()call leaves contradictory discriminator filters behind while#variantNameonly remembers the last choice. Track the selected variant separately and merge its discriminator only when building the actual query/write filter.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts` around lines 143 - 166, The variant() method currently appends the discriminator predicate into the private `#state.filters` which lets calls like .variant(...).update/delete/upsert() bypass explicit .where() and leaves stale contradictory filters when variant() is called multiple times; instead, stop pushing the discriminator into `#state.filters` in variant(), and record the chosen variant separately in the collection state (e.g. set a dedicated state property like variantName or selectedVariant via `#cloneWithVariant`); update `#cloneWithVariant` to copy that variant marker rather than adding a filter, and ensure the actual query/write paths (the code that builds final filters and `#requireFilters`() checks) merge the discriminator predicate derived from model.discriminator and the recorded variant only at query/write-building time so multiple variant() calls only reflect the last selected variant and do not alter `#state.filters` directly.
🧹 Nitpick comments (2)
examples/mongo-demo/src/app/styles.css (1)
127-130: Consider using a CSS variable for tutorial background.
.card-articleusesvar(--feature-bg)while.card-tutorialuses a hardcoded hex value#111d15. For consistency and easier theme maintenance, consider adding a--low-bgor--tutorial-bgvariable.♻️ Suggested refactor
Add a CSS variable in
:root:--low: `#22c55e`; + --low-bg: `#111d15`;Then use it in
.card-tutorial:.card-tutorial { border-left: 3px solid var(--low); - background: `#111d15`; + background: var(--low-bg); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/mongo-demo/src/app/styles.css` around lines 127 - 130, The .card-tutorial rule currently hardcodes background `#111d15`; add a CSS variable in :root (e.g., --tutorial-bg or --low-bg) alongside existing variables like --feature-bg, then replace the hardcoded color in the .card-tutorial selector with var(--tutorial-bg) to keep theming consistent with .card-article and make future theme changes easier.packages/2-mongo-family/5-query-builders/orm/src/collection.ts (1)
221-228: Avoid reintroducing a blind cast ininclude().This is the same type hole
#cloneWithVariant()was added to avoid. A typed clone helper for include transitions keeps the fluent API sound without asserting throughunknown. As per coding guidelines, "No blind casts in production code:as unknown as Xis forbidden outside tests. Prefer type predicates or fix the type surface."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts` around lines 221 - 228, The include() method is reintroducing a blind cast (as unknown as MongoCollectionImpl) which we avoided with `#cloneWithVariant`(); replace the blind cast by creating or using a typed clone helper for include transitions (e.g., `#cloneWithInclude` or extend `#cloneWithVariant` to accept include type changes) that returns MongoCollectionImpl<TContract, ModelName, TIncludes & Record<K, true>, TVariant> and call that instead of this.#clone({...}) as unknown as .... Ensure the helper accepts the new includes array (constructed from this.#state.includes and includeExpr), preserves runtime cloning behavior currently done by `#clone`, and is properly generic so the fluent API remains type-safe without assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 249-254: The removal currently deletes
roots[variantCollectionName] when roots[variantCollectionName] === variantName,
which drops the base when a Variant explicitly @@map()s to the same collection
as its Base; instead, when removing the variant entry, check the variant's base
(access via variantPslModel.base or the appropriate property that points to the
Base model) and if that base exists and should own the collection, restore
roots[variantCollectionName] = <baseName> (otherwise remove the entry); update
the code around resolveCollectionName, variantPslModel and variantName to
perform this conditional restore rather than unconditionally filtering the key
out.
---
Outside diff comments:
In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts`:
- Around line 398-423: The upsert path lets update fields overwrite the selected
variant because `#injectDiscriminator` is only applied to input.create while
`#toSetFields`(input.update) can include the discriminator; change the update
normalization so the discriminator cannot be set: either have the shared update
normalization (the function that `#toSetFields` calls) strip/reject the
discriminator key or have upsert explicitly remove the discriminator from
setFields (and/or call `#injectDiscriminator` on the update-normalizer) before
building updateDoc; update the code paths using `#toSetFields` (including upsert
and other update* methods) so they consistently refuse or ignore writes to the
model discriminator (use the internal discriminator identifier used elsewhere in
the class such as the discriminator field constant/member).
- Around line 45-114: The collection's TVariant is applied to inputs but not to
outputs—methods first(), all(), create(), createAll(), and upsert() return
IncludedRow<TContract,ModelName,TIncludes> instead of a variant-narrowed row;
update the return types to thread TVariant through by using
VariantModelRow<TContract,ModelName,TVariant> (or a small helper type that
resolves to DefaultModelRow/VariantModelRow when TVariant is never) and wrap
that in IncludedRow<TContract,ModelName,TIncludes, /* variant-aware row */>;
change signatures on first(), all(), create(), createAll(), and upsert() to use
this variant-aware result type so .variant('X').first() yields the narrowed
variant row.
---
Duplicate comments:
In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts`:
- Around line 143-166: The variant() method currently appends the discriminator
predicate into the private `#state.filters` which lets calls like
.variant(...).update/delete/upsert() bypass explicit .where() and leaves stale
contradictory filters when variant() is called multiple times; instead, stop
pushing the discriminator into `#state.filters` in variant(), and record the
chosen variant separately in the collection state (e.g. set a dedicated state
property like variantName or selectedVariant via `#cloneWithVariant`); update
`#cloneWithVariant` to copy that variant marker rather than adding a filter, and
ensure the actual query/write paths (the code that builds final filters and
`#requireFilters`() checks) merge the discriminator predicate derived from
model.discriminator and the recorded variant only at query/write-building time
so multiple variant() calls only reflect the last selected variant and do not
alter `#state.filters` directly.
---
Nitpick comments:
In `@examples/mongo-demo/src/app/styles.css`:
- Around line 127-130: The .card-tutorial rule currently hardcodes background
`#111d15`; add a CSS variable in :root (e.g., --tutorial-bg or --low-bg) alongside
existing variables like --feature-bg, then replace the hardcoded color in the
.card-tutorial selector with var(--tutorial-bg) to keep theming consistent with
.card-article and make future theme changes easier.
In `@packages/2-mongo-family/5-query-builders/orm/src/collection.ts`:
- Around line 221-228: The include() method is reintroducing a blind cast (as
unknown as MongoCollectionImpl) which we avoided with `#cloneWithVariant`();
replace the blind cast by creating or using a typed clone helper for include
transitions (e.g., `#cloneWithInclude` or extend `#cloneWithVariant` to accept
include type changes) that returns MongoCollectionImpl<TContract, ModelName,
TIncludes & Record<K, true>, TVariant> and call that instead of
this.#clone({...}) as unknown as .... Ensure the helper accepts the new includes
array (constructed from this.#state.includes and includeExpr), preserves runtime
cloning behavior currently done by `#clone`, and is properly generic so the fluent
API remains type-safe without assertions.
🪄 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: 4633bfaa-5dbc-4f79-9ced-c76f433b22af
📒 Files selected for processing (10)
examples/mongo-demo/src/app/App.tsxexamples/mongo-demo/src/app/PostList.tsxexamples/mongo-demo/src/app/styles.cssexamples/mongo-demo/src/server.tspackages/1-framework/2-authoring/psl-parser/src/attribute-helpers.tspackages/1-framework/2-authoring/psl-parser/src/exports/index.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.tspackages/2-mongo-family/5-query-builders/orm/src/collection.tspackages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.ts
✅ Files skipped from review due to trivial changes (3)
- examples/mongo-demo/src/app/App.tsx
- packages/1-framework/2-authoring/psl-parser/src/exports/index.ts
- packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- examples/mongo-demo/src/server.ts
b178b3e to
6ec63d0
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 171-203: The discriminator logic is comparing and storing the PSL
field name (decl.fieldName) while model.fields is keyed by the mapped (database)
name; change the code in the discriminator handling to resolve the mapped field
name first by finding the entry in model.fields whose field.pslName or
equivalent PSL identifier matches decl.fieldName, then use that mapped key for
the existence check (replace Object.hasOwn(model.fields, decl.fieldName)) and
store discriminator.field as the mapped name (instead of decl.fieldName) when
you build patched[modelName].discriminator; keep the rest of the variant logic
unchanged.
🪄 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: 85d81c42-b691-4212-bd77-79c5211747f1
📒 Files selected for processing (2)
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
f68676b to
0aa8e49
Compare
…205) Spec covers PSL authoring (@@discriminator/@@base), SQL ORM discriminated union types, .variant() narrowing API, STI and MTI query compilation, and Mongo variant support. Plan has 6 milestones: PSL authoring, SQL types + .variant(), SQL STI runtime, SQL MTI runtime, Mongo .variant() + integration tests, and demo app integration for both families.
…support Implement polymorphism in the SQL PSL interpreter: - Collect @@Discriminator(fieldName) and @@base(BaseModel, "value") declarations - Cross-reference and validate: field existence, mutual exclusivity, orphaned declarations, duplicate discriminator values, non-existent base targets - Resolve variant storage: STI (no @@Map, inherits base table) or MTI (own table) - Exclude variant models from roots - Skip PK requirement for variant models (they inherit from base)
…e support Implement polymorphism in the Mongo PSL interpreter: - Collect @@Discriminator and @@base declarations, validate cross-references - Enforce single-collection: variant with @@Map to different collection is diagnosed - Variant inherits base collection, excluded from roots - Diagnostics for orphaned declarations, missing discriminator field, conflicting attributes, and non-existent base targets
… test for polymorphism Verify that a polymorphic contract produced by the interpreter passes domain validation (discriminator/variants/base cross-referencing).
…olymorphism Add VariantRow and InferRootRow type utilities that produce discriminated union types for polymorphic base models. For non-polymorphic models, the type falls through to DefaultModelRow. Discriminator field narrows to literal string values from the variants map.
…arrowing Add variant() to Collection that: - Stores variant name in CollectionState - Injects discriminator equality filter for the variant value - Narrows the Row type parameter to the specific variant row Also add VariantNames and VariantModelRow helper types.
…ction Add VariantNames, VariantModelRow types and .variant() API on MongoCollection. The method injects a discriminator eq filter and narrows the return type to the selected variant. Includes type tests for discriminated union narrowing and unit tests for runtime filter injection and immutability.
Add Article/Tutorial variants to the Post model in contract.prisma, re-emit the contract, and wire .variant() queries with API endpoints. Skip @id check for variant models in the Mongo PSL interpreter. Update seed data and tests to include the new kind discriminator.
The SQL emitter generateModelsType was missing polymorphism properties that the shared (Mongo) emitter already handles. Also fix STI-vs-MTI detection to check for explicit @@Map attribute rather than comparing the table name to the lowered model name.
Add Task model with @@Discriminator(type) and Bug/Feature variants using MTI (@@Map to separate tables). Wire TaskCollection with .bugs()/.features() scopes and add repo-tasks/repo-bugs/repo-features CLI commands. Re-emit contract and adapt integration test.
Change the Collection class and orm() factory default Row type parameter from DefaultModelRow to InferRootRow. For non-polymorphic models this is a no-op (InferRootRow falls through to DefaultModelRow). For polymorphic roots it causes all()/first()/create() etc to return the discriminated union by default without requiring .variant().
Add TVariant type parameter to MongoCollection so .variant("Bug")
carries the variant name through to create/createAll/upsert methods.
VariantCreateInput omits the discriminator field (auto-injected at
runtime) and includes only base + variant-specific fields minus _id.
ResolvedCreateInput conditionally selects between CreateInput and
VariantCreateInput based on whether a variant is active.
At runtime, when a variant is set, create/createAll/createCount/upsert
inject the discriminator field and value into each document.
…erver Verify the full polymorphism flow against a real MongoDB instance: - base query returns rows with discriminator values - variant() filters to the correct subset - variant create injects discriminator and persists it - round-trip: create via variant, read back via base - non-polymorphic models are unaffected - variant first()/createAll() work correctly
The spec requires the TS authoring DSL (contract-ts) to support polymorphism, not just the PSL interpreters. Add Milestone 6 with tasks for StagedModelBuilder.discriminator()/.base(), semantic IR extensions, and lowering pipeline changes. Renumber demo apps to M7.
…to psl-parser Both SQL and Mongo contract-psl packages had near-identical implementations of these PSL attribute helpers. Move the canonical definitions to the shared psl-parser package and re-export from the original modules to avoid breaking existing import sites.
Replace in-place model mutations with immutable spread pattern, mirroring the SQL interpreter. Extract inline polymorphism block into collectPolymorphismDeclarations and resolvePolymorphism functions that return new model/roots records instead of mutating the originals.
…thVariant Add a generic #cloneWithVariant<VNew> that produces a new instance typed with the target variant, removing the as-unknown-as cast on the happy path. The two early-return casts remain with comments explaining that returning this as a narrowed type requires a cast.
Seed data now uses .variant("Article") and .variant("Tutorial") creates
with variant-specific fields (summary, difficulty, duration). PostList
switches on post.kind to render ArticleCard and TutorialCard with
access to the narrowed discriminated union fields.
…ame collection When a variant model explicitly @@Map()s to the same collection as its base, the root removal logic was deleting the entry entirely instead of restoring the base model as the root owner. Also validates that Mongo discriminator fields are String type.
Add validation that @@Discriminator field must be of type String, with a clear diagnostic message and test coverage.
…nt() calls When calling .variant() on a collection that already has a variant filter, strip the previous discriminator filter before adding the new one. Also fix type test casts for discriminated union narrowing.
The contract.d.ts format changed in main (model type generation extracted to framework). Re-emit to pick up the new format while preserving polymorphism metadata.
Cover getPositionalArgument and parseQuotedStringLiteral extracted in F06, and the new Collection.variant() method including filter injection, variant chaining, and non-variant filter preservation.
0aa8e49 to
4c62e4c
Compare
closes TML-2205
Key snippet (new capability)
Intent
Make polymorphism a first-class authoring and query surface for both SQL and Mongo ORMs. Users write
@@discriminatorand@@basein PSL, the contract carries the polymorphism metadata, and ORM collections expose a.variant()method that injects discriminator filters and narrows the return type.This PR delivers: PSL authoring in both interpreters, type-level polymorphism (
InferRootRowdiscriminated unions), the.variant()API with full type narrowing and discriminator auto-injection on writes (Mongo), SQL emitter support, Mongo integration tests, and demo apps.SQL runtime query compilation (STI/MTI) follows in TML-2227. TS authoring DSL polymorphism follows in TML-2228.
Change map
The story
PSL authoring: teach both interpreters
@@discriminatorand@@base. The PSL parser already handles generic model-level attributes, so no parser changes were needed. Each interpreter collects@@discriminatorand@@basedeclarations in a post-processing pass after all models are built, validates bidirectional consistency, and patches the models withdiscriminator/variants/baseproperties. Variant models are stripped fromroots. The SQL interpreter also derives STI (no@@map→ shared table) vs MTI (@@map→ own table). The Mongo interpreter enforces single-collection (rejects@@mapto a different collection).Type-level discriminated unions for both ORMs. The Mongo ORM already had
InferRootRow/VariantRow. The SQL ORM gets the same pattern:InferRootRow<Contract, 'Task'>produces a union of(base fields − discriminator) & variant fields & Record<discriminator, literal>for each variant. Non-polymorphic models fall through toDefaultModelRow. The SQLCollectionandorm()factory now default toInferRootRowso polymorphic roots return the discriminated union automatically..variant()with full type narrowing on both collections. Both SQL and Mongo collections get a.variant(variantName)method that reads the discriminator field/value from the contract and injects an equality filter. Both narrow theRowtype parameter toVariantModelRow. The Mongo collection adds aTVarianttype parameter that threads through all chained methods (where,take,select, etc.) and controlsCreateInputnarrowing.Variant-aware writes with discriminator auto-injection (Mongo).
VariantCreateInput<Contract, 'Task', 'Bug'>includes base + variant fields, excludes_idand the discriminator field. When creating through a variant collection,#injectDiscriminatorautomatically adds the discriminator field/value to the insert document.ResolvedCreateInputconditionally selects betweenCreateInput(base) andVariantCreateInput(variant) based on theTVarianttype parameter.SQL emitter: emit polymorphism metadata in
contract.d.ts. The framework emitter already handles Mongocontract.d.ts. The SQL emitter needed the same treatment — emittingreadonly discriminator,readonly variants, andreadonly baseproperties on models that carry them.Mongo integration tests against mongodb-memory-server. Dedicated integration tests verify: variant filtering, variant
create()auto-injects discriminator, base query returns all variants, non-polymorphic models unaffected, variantfirst(), variantcreateAll().Demo apps prove the full path. Both demos add polymorphic models to their PSL schemas, re-emit contracts, and exercise
.variant()queries. The Mongo demo adds API endpoints and an integration test.Behavior changes & evidence
PSL
@@discriminatorand@@baseare now recognized by both interpreters: Adds contract authoring for polymorphism. Previously, polymorphic contracts could only be hand-crafted as JSON fixtures.SQL ORM
Collection.all()returns a discriminated union for polymorphic roots by default:InferRootRowis now the defaultRowtype parameter onCollectionandorm(). Non-polymorphic models are unaffected (fall through toDefaultModelRow)..variant()method on both ORM collections injects discriminator filter and narrows the row type: Calling.variant('Bug')prepends a discriminator equality filter, narrows theRowtype toVariantModelRow, and (for Mongo) narrowsCreateInputtoVariantCreateInput.SQL emitter emits
discriminator/variants/baseincontract.d.ts: Previously the SQL emitter did not include these properties..d.tstypes lacked the polymorphism metadata needed byInferRootRowand.variant().contract.d.tscontaining the metadata.Compatibility / migration / risk
Not in scope (follow-ups)
findModelNameForTablefix, SQL.variant()write support, Postgres integration tests → TML-2227StagedModelBuilder.discriminator()/.base(), semantic IR extensions, lowering pipeline → TML-2228Non-goals
.where()narrowing — future type-level enhancement.Summary by CodeRabbit
New Features
Tests