Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

feat(orm): add polymorphism authoring, types, and Mongo runtime via @@discriminator/@@base - #315

Merged
wmadden merged 26 commits into
mainfrom
tml-2205-polymorphism-in-both-families-adr-173
Apr 9, 2026
Merged

wmadden merged 26 commits into
mainfrom
tml-2205-polymorphism-in-both-families-adr-173

Conversation

@wmadden

@wmadden wmadden commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-2205

Key snippet (new capability)

// SQL ORM — variant narrowing API
export class TaskCollection extends Collection<Contract, 'Task'> {
  bugs() {
    return this.variant('Bug');
  }
  features() {
    return this.variant('Feature');
  }
}

// Usage — discriminated union by default, narrowed via .variant()
const tasks = await db.Task.take(10).all();        // returns discriminated union
const bugs = await db.Task.bugs().take(10).all();   // narrowed to Bug row type
const features = await db.Task.features().all();    // narrowed to Feature row type

Intent

Make polymorphism a first-class authoring and query surface for both SQL and Mongo ORMs. Users write @@discriminator and @@base in 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 (InferRootRow discriminated 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

  1. PSL authoring: teach both interpreters @@discriminator and @@base. The PSL parser already handles generic model-level attributes, so no parser changes were needed. Each interpreter collects @@discriminator and @@base declarations in a post-processing pass after all models are built, validates bidirectional consistency, and patches the models with discriminator/variants/base properties. Variant models are stripped from roots. The SQL interpreter also derives STI (no @@map → shared table) vs MTI (@@map → own table). The Mongo interpreter enforces single-collection (rejects @@map to a different collection).

  2. 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 to DefaultModelRow. The SQL Collection and orm() factory now default to InferRootRow so polymorphic roots return the discriminated union automatically.

  3. .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 the Row type parameter to VariantModelRow. The Mongo collection adds a TVariant type parameter that threads through all chained methods (where, take, select, etc.) and controls CreateInput narrowing.

  4. Variant-aware writes with discriminator auto-injection (Mongo). VariantCreateInput<Contract, 'Task', 'Bug'> includes base + variant fields, excludes _id and the discriminator field. When creating through a variant collection, #injectDiscriminator automatically adds the discriminator field/value to the insert document. ResolvedCreateInput conditionally selects between CreateInput (base) and VariantCreateInput (variant) based on the TVariant type parameter.

  5. SQL emitter: emit polymorphism metadata in contract.d.ts. The framework emitter already handles Mongo contract.d.ts. The SQL emitter needed the same treatment — emitting readonly discriminator, readonly variants, and readonly base properties on models that carry them.

  6. 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, variant first(), variant createAll().

  7. 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 @@discriminator and @@base are 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: InferRootRow is now the default Row type parameter on Collection and orm(). Non-polymorphic models are unaffected (fall through to DefaultModelRow).

  • .variant() method on both ORM collections injects discriminator filter and narrows the row type: Calling .variant('Bug') prepends a discriminator equality filter, narrows the Row type to VariantModelRow, and (for Mongo) narrows CreateInput to VariantCreateInput.

  • SQL emitter emits discriminator/variants/base in contract.d.ts: Previously the SQL emitter did not include these properties.

    • Why: Without this, the emitted .d.ts types lacked the polymorphism metadata needed by InferRootRow and .variant().
    • Implementation: emitter/src/index.ts
    • Tests: Validated by the SQL demo's re-emitted contract.d.ts containing the metadata.

Compatibility / migration / risk

  • No breaking changes to existing APIs. This is purely additive.

Not in scope (follow-ups)

  • SQL STI/MTI runtime (M3, M4) — query compilation, result mapping, write compilation, findModelNameForTable fix, SQL .variant() write support, Postgres integration tests → TML-2227
  • SQL TS authoring DSL (M6) — StagedModelBuilder.discriminator()/.base(), semantic IR extensions, lowering pipeline → TML-2228

Non-goals

  • Discriminator-aware .where() narrowing — future type-level enhancement.
  • Multi-level polymorphism — not yet designed.
  • Concrete table inheritance — not planned.
  • Polymorphic value objects — deferred to Phase 1.75c.

Summary by CodeRabbit

  • New Features

    • Polymorphic model support via discriminators and bases (discriminated union types) for MongoDB and SQL.
    • .variant() APIs for type-safe filtering, querying, and creating variant-specific records.
    • Example apps updated: UI now renders Article vs Tutorial posts, new API endpoints for articles/tutorials, and CLI commands to list tasks/bugs/features.
  • Tests

    • Extensive tests covering polymorphic queries, mutations, type-narrowing, and end-to-end examples.

@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
Examples — Mongo demo
examples/mongo-demo/prisma/contract.prisma, examples/mongo-demo/src/contract.d.ts, examples/mongo-demo/src/contract.json, examples/mongo-demo/src/server.ts, examples/mongo-demo/test/blog.test.ts, examples/mongo-demo/src/app/PostList.tsx, examples/mongo-demo/src/app/App.tsx, examples/mongo-demo/src/app/styles.css
Add kind discriminator to Post (@@discriminator(kind)), introduce Article/Tutorial variants (@@base(Post, ...)) sharing posts collection; update generated contract/artifacts, server endpoints (getArticles/getTutorials), seed/tests, UI rendering and styles.
Examples — Prisma/SQL demo
examples/prisma-next-demo/prisma/schema.prisma, examples/prisma-next-demo/src/prisma/contract.d.ts, examples/prisma-next-demo/src/prisma/contract.json, examples/prisma-next-demo/src/main.ts, examples/prisma-next-demo/src/orm-client/*, examples/prisma-next-demo/test/*
Add Task base with @@discriminator(type) and Bug/Feature variants (@@base(Task, ...)), add User.tasks relation and task roots/tables, update contract hashes, add ORM client helpers/CLI branches and tests.
PSL — Mongo interpreter & helpers
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts, packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts, packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
Collect and validate @@discriminator/@@base attributes, emit polymorphism diagnostics, resolve and patch models with discriminator/variants/base, enforce single-collection constraints, relax missing-@id for @@base, adjust roots, and add tests.
PSL — SQL interpreter & tests
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts, packages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.ts
Parse @@discriminator/@@base, validate cross-model rules, inject discriminator/variants/base, handle STI vs MTI storage mapping, filter variant roots, re-export positional/quoted helpers, and add diagnostics/tests.
Mongo ORM — Query builder/types/exports/tests
packages/2-mongo-family/5-query-builders/orm/src/collection.ts, packages/2-mongo-family/5-query-builders/orm/src/types.ts, packages/2-mongo-family/5-query-builders/orm/src/exports/index.ts, packages/2-mongo-family/5-query-builders/orm/package.json, packages/2-mongo-family/5-query-builders/orm/test/*
Add TVariant generic and variant() API to MongoCollection, thread variant through chainable methods, inject discriminator into read filters and write payloads, add Variant*/ResolvedCreateInput types and re-exports, update dev deps, and add unit/integration/type tests.
SQL ORM — Collection/types/orm/emitter/tests
packages/3-extensions/sql-orm-client/src/collection.ts, packages/3-extensions/sql-orm-client/src/types.ts, packages/3-extensions/sql-orm-client/src/orm.ts, packages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts, packages/2-sql/3-tooling/emitter/src/index.ts
Add variant() to SQL Collection (appends discriminator equality predicate), change default root row to InferRootRow, add variantName state and InferRootRow/VariantNames/VariantModelRow types, update emitter to emit optional discriminator/variants/base in model types, and add compile-time tests.
Parser helpers & exports
packages/1-framework/2-authoring/psl-parser/src/attribute-helpers.ts, packages/1-framework/2-authoring/psl-parser/src/exports/index.ts, packages/2-sql/.../psl-attribute-parsing.ts
Introduce shared helpers getPositionalArgument and parseQuotedStringLiteral in parser exports; other modules re-export/use these helpers.
Tests & tooling adjustments
packages/.../test/*, examples/.../test/*
Add extensive new tests (unit, integration, type-level) validating polymorphism semantics, diagnostics, ORM reads/writes, and end-to-end contract/validation flows across SQL and Mongo stacks.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Poem

🐇 I nibbled at schemas, traced each kind and base,

Mapped Articles, Bugs, Features—lined up in a race.
Discriminators hum; variants snug and neat,
Reads and writes align, the rabbit hops in beat! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.70% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main feature being added: polymorphism support through @@discriminator/@@base attributes in the ORM. It is concise, specific, and directly reflects the primary change in the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2205-polymorphism-in-both-families-adr-173

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Apr 8, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@315

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@315

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@315

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@315

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@315

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@315

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@315

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@315

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@315

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@315

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@315

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@315

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@315

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@315

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@315

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@315

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@315

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@315

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@315

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@315

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@315

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@315

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@315

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@315

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@315

@prisma-next/runtime-executor

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/runtime-executor@315

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@315

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@315

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@315

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@315

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@315

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@315

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@315

@prisma-next/mongo-pipeline-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-pipeline-builder@315

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@315

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@315

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@315

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@315

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@315

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@315

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@315

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@315

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@315

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@315

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@315

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@315

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@315

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@315

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@315

commit: 4c62e4c

@wmadden
wmadden force-pushed the tml-2205-polymorphism-in-both-families-adr-173 branch from 3e7c7a7 to 01e0631 Compare April 8, 2026 10:21

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🟡 Minor

Usage string missing new commands.

The help text doesn't include repo-tasks, repo-bugs, or repo-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 | 🟠 Major

Build the top-level ORM surface from contract.roots, not contract.models.

interpretPslDocumentToSqlContract() now removes variant models from contract.roots, but this proxy still enumerates and validates against the full contract.models set. That keeps orm.Bug / orm.Feature publicly reachable even though the PR makes variants non-roots, and it bypasses the new root boundary entirely. Filter both modelNames and custom-collection registration to roots (or models without base) 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 toMatchObject for 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.ts is 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 like collection.variant.test.ts or collection.polymorphism.test.ts would 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 since MutableDomainModel doesn't declare discriminator or variants properties. Consider whether extending MutableDomainModel with 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.ts files 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9161a4b and e945c86.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/orm-consolidation/plans/phase-1.75b-polymorphism-plan.md is excluded by !projects/**
  • projects/orm-consolidation/specs/polymorphism.spec.md is excluded by !projects/**
📒 Files selected for processing (30)
  • examples/mongo-demo/prisma/contract.prisma
  • examples/mongo-demo/src/contract.d.ts
  • examples/mongo-demo/src/contract.json
  • examples/mongo-demo/src/server.ts
  • examples/mongo-demo/test/blog.test.ts
  • examples/prisma-next-demo/prisma/schema.prisma
  • examples/prisma-next-demo/src/main.ts
  • examples/prisma-next-demo/src/orm-client/client.ts
  • examples/prisma-next-demo/src/orm-client/collections.ts
  • examples/prisma-next-demo/src/orm-client/get-tasks.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/test/demo-dx.integration.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-mongo-family/5-query-builders/orm/package.json
  • packages/2-mongo-family/5-query-builders/orm/src/collection.ts
  • packages/2-mongo-family/5-query-builders/orm/src/exports/index.ts
  • packages/2-mongo-family/5-query-builders/orm/src/types.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-mongo-family/5-query-builders/orm/test/orm-types.test-d.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-sql/3-tooling/emitter/src/index.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/orm.ts
  • packages/3-extensions/sql-orm-client/src/types.ts
  • packages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (2)

384-385: ⚠️ Potential issue | 🔴 Critical

Own-table variants still have no contract-level link back to the base row.

Skipping the PK requirement for @@base models and then only rewriting storage.table lets @@base(...)+@@map(...) emit standalone variant tables with no primary key or FK to the base model. The generated demo contract already has bug/feature tables with only variant-local columns, so a Task variant row cannot be uniquely identified or hydrated from the contract. Safest short-term fix is to reject explicit @@map on 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 | 🟠 Major

Reject non-string discriminator fields.

You parse @@base(..., "bug") values as strings, but this validation only checks that the referenced discriminator field exists. An Int, JSON, or value-object field will still pass here even though downstream variants[].value metadata and SQL variant() 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 both Article and Video), both would be stored in variants without error, but only one would survive since they'd have the same key. However, the issue is if two different variants map to the same value string—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

📥 Commits

Reviewing files that changed from the base of the PR and between e945c86 and 01e0631.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/orm-consolidation/plans/phase-1.75b-polymorphism-plan.md is excluded by !projects/**
  • projects/orm-consolidation/specs/polymorphism.spec.md is excluded by !projects/**
📒 Files selected for processing (30)
  • examples/mongo-demo/prisma/contract.prisma
  • examples/mongo-demo/src/contract.d.ts
  • examples/mongo-demo/src/contract.json
  • examples/mongo-demo/src/server.ts
  • examples/mongo-demo/test/blog.test.ts
  • examples/prisma-next-demo/prisma/schema.prisma
  • examples/prisma-next-demo/src/main.ts
  • examples/prisma-next-demo/src/orm-client/client.ts
  • examples/prisma-next-demo/src/orm-client/collections.ts
  • examples/prisma-next-demo/src/orm-client/get-tasks.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/test/demo-dx.integration.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-mongo-family/5-query-builders/orm/package.json
  • packages/2-mongo-family/5-query-builders/orm/src/collection.ts
  • packages/2-mongo-family/5-query-builders/orm/src/exports/index.ts
  • packages/2-mongo-family/5-query-builders/orm/src/types.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-mongo-family/5-query-builders/orm/test/orm-types.test-d.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-sql/3-tooling/emitter/src/index.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/orm.ts
  • packages/3-extensions/sql-orm-client/src/types.ts
  • packages/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

@wmadden
wmadden force-pushed the tml-2205-polymorphism-in-both-families-adr-173 branch from 01e0631 to 78d9147 Compare April 8, 2026 14:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

TVariant is threaded into write inputs via ResolvedCreateInput<..., TVariant>, but every read/mutation return type still uses IncludedRow<TContract, ModelName, TIncludes>, which doesn't accept a variant parameter and returns the full root union instead of the narrowed variant. The VariantModelRow<TContract, ModelName, V> helper exists but is never used in the collection surface. Update IncludedRow to accept TVariant and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 01e0631 and 78d9147.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/orm-consolidation/plans/phase-1.75b-polymorphism-plan.md is excluded by !projects/**
  • projects/orm-consolidation/specs/polymorphism.spec.md is excluded by !projects/**
📒 Files selected for processing (30)
  • examples/mongo-demo/prisma/contract.prisma
  • examples/mongo-demo/src/contract.d.ts
  • examples/mongo-demo/src/contract.json
  • examples/mongo-demo/src/server.ts
  • examples/mongo-demo/test/blog.test.ts
  • examples/prisma-next-demo/prisma/schema.prisma
  • examples/prisma-next-demo/src/main.ts
  • examples/prisma-next-demo/src/orm-client/client.ts
  • examples/prisma-next-demo/src/orm-client/collections.ts
  • examples/prisma-next-demo/src/orm-client/get-tasks.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/test/demo-dx.integration.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-mongo-family/5-query-builders/orm/package.json
  • packages/2-mongo-family/5-query-builders/orm/src/collection.ts
  • packages/2-mongo-family/5-query-builders/orm/src/exports/index.ts
  • packages/2-mongo-family/5-query-builders/orm/src/types.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-mongo-family/5-query-builders/orm/test/orm-types.test-d.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-sql/3-tooling/emitter/src/index.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/orm.ts
  • packages/3-extensions/sql-orm-client/src/types.ts
  • packages/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

@wmadden wmadden changed the title feat(orm): add polymorphism via @@discriminator and @@base feat(orm): add polymorphism authoring, types, and Mongo runtime via @@discriminator/@@base Apr 8, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.update can defeat the active variant on insert.

#injectDiscriminator() only normalizes input.create, but #toSetFields() still accepts the discriminator field. Because $set wins over $setOnInsert, collection.variant('Bug').upsert(...) can insert a non-Bug document on the no-match path. This guard probably belongs in the shared update normalization so update*() 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 | 🟠 Major

Thread TVariant into result types using VariantModelRow.

The TVariant generic in MongoCollection correctly narrows write inputs via ResolvedCreateInput<..., TVariant>, but all result-returning methods (first(), all(), create(), createAll(), upsert()) return IncludedRow<TContract, ModelName, TIncludes> without using TVariant. 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. Update IncludedRow or introduce a variant-aware result type that uses TVariant when it's not never.

🤖 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 | 🔴 Critical

Still 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 second variant() call leaves contradictory discriminator filters behind while #variantName only 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-article uses var(--feature-bg) while .card-tutorial uses a hardcoded hex value #111d15. For consistency and easier theme maintenance, consider adding a --low-bg or --tutorial-bg variable.

♻️ 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 in include().

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 through unknown. As per coding guidelines, "No blind casts in production code: as unknown as X is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 78d9147 and db7c49a.

📒 Files selected for processing (10)
  • examples/mongo-demo/src/app/App.tsx
  • examples/mongo-demo/src/app/PostList.tsx
  • examples/mongo-demo/src/app/styles.css
  • examples/mongo-demo/src/server.ts
  • packages/1-framework/2-authoring/psl-parser/src/attribute-helpers.ts
  • packages/1-framework/2-authoring/psl-parser/src/exports/index.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
  • packages/2-mongo-family/5-query-builders/orm/src/collection.ts
  • packages/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

@wmadden
wmadden force-pushed the tml-2205-polymorphism-in-both-families-adr-173 branch from b178b3e to 6ec63d0 Compare April 8, 2026 16:24

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between db7c49a and b178b3e.

📒 Files selected for processing (2)
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/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

@wmadden
wmadden force-pushed the tml-2205-polymorphism-in-both-families-adr-173 branch 2 times, most recently from f68676b to 0aa8e49 Compare April 8, 2026 18:10
wmadden added 17 commits April 9, 2026 06:10
…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.
wmadden added 9 commits April 9, 2026 06:10
…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.
@wmadden
wmadden force-pushed the tml-2205-polymorphism-in-both-families-adr-173 branch from 0aa8e49 to 4c62e4c Compare April 9, 2026 04:12
@wmadden
wmadden merged commit 5ced9f2 into main Apr 9, 2026
15 checks passed
@wmadden
wmadden deleted the tml-2205-polymorphism-in-both-families-adr-173 branch April 9, 2026 04:31
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant