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

feat(sql-orm-client): add STI and MTI polymorphism runtime - #321

Merged
wmadden merged 26 commits into
mainfrom
tml-2227-sql-orm-polymorphism-runtime-sti-mti
Apr 10, 2026
Merged

wmadden merged 26 commits into
mainfrom
tml-2227-sql-orm-polymorphism-runtime-sti-mti

Conversation

@wmadden

@wmadden wmadden commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-2227

Walkthrough — SQL ORM Polymorphism Runtime (STI + MTI)

Intent

Make the SQL ORM's .variant() API functionally complete by implementing STI and MTI query compilation, discriminator-aware result mapping, variant-aware writes, and the model-first mapping refactor that underpins it all. TML-2205 established the type-level foundation and .variant() stub; this work makes the SQL runtime actually deliver polymorphic rows.

Change map

The story

  1. Introduce strategy resolution. resolvePolymorphismInfo reads a base model's discriminator and variants metadata from the contract. For each variant, it compares the variant's storage.table to the base's — same table means STI, different table means MTI. The result is a cached PolymorphismInfo structure with strategy: 'sti' | 'mti' per variant.

  2. Refactor mapping to be model-first. The existing dispatch/mapping path threaded tableName and used findModelNameForTable to reverse-lookup the model. This breaks under STI where multiple models share a table. The refactor makes modelName required in mapStorageRowToModelFields, stripHiddenMappedFields, createRowEnvelope, and all dispatch/mutation-dispatch functions. findModelNameForTable is removed entirely.

  3. Add discriminator-aware result mapping. mapPolymorphicRow inspects the discriminator column in each raw row to determine the variant, then builds a merged base + variant column→field map. For MTI variants, the map uses table-qualified keys (${table}__${col}) matching the query aliases. Only columns in the merged map appear in the output. Unknown discriminator values fall back to base-only mapping.

  4. Compile MTI JOINs with table-qualified aliases. buildMtiJoins generates LEFT JOINs (base queries) or INNER JOINs (variant queries) to MTI variant tables. Variant columns are projected with ${variant.table}__${col} aliases to prevent collisions when multiple MTI variants share column names. Applied in both compileSelect and compileSelectWithIncludeStrategy.

  5. Implement variant-aware writes. STI writes go through #mapCreateRows, which merges base + variant field→column maps and injects the discriminator value. MTI writes go through #executeMtiCreate, which splits input into base and variant fields, executes a base INSERT RETURNING for the PK, calls applyCreateDefaults on both tables, then executes a variant INSERT. The returned merged row uses table-prefixed keys for mapPolymorphicRow.

  6. Guard MTI-incompatible mutations. createCount and upsert throw at runtime for MTI variants via #assertNotMtiVariant.

  7. Gate writes behind .variant() at the type level. ResolvedCreateInput resolves to never for polymorphic bases without a variant name, making create() on a bare polymorphic collection a compile-time error.

  8. Extract shared test helpers. buildMixedPolyContract() and buildStiPolyContract() consolidated into test/helpers.ts, eliminating duplication across four test files.

Behavior changes & evidence

  • Adds PolymorphismInfo strategy resolution (STI vs MTI from storage table comparison)

  • Removes findModelNameForTable, makes modelName required in all mapping functions

  • Adds mapPolymorphicRow() with table-qualified MTI alias resolution

  • Adds MTI JOIN compilation with ${table}__${col} aliases in both standalone and include paths

    • Why: MTI data lives on separate tables. Table-qualified aliases prevent column name collisions.
    • Implementation: query-plan-select.ts — buildMtiJoins, used in compileSelect and compileSelectWithIncludeStrategy
    • Tests: query-plan-select.test.ts — 5 tests (expects features__priority)
  • Adds STI variant write with discriminator auto-injection

  • Adds MTI variant write with two-INSERT orchestration and defaults on both tables

    • Why: MTI data spans two tables. applyCreateDefaults on both ensures variant table defaults are applied.
    • Implementation: collection.ts — #executeMtiCreate
    • Tests: collection-variant.test.ts — 1 test
  • Guards createCount and upsert against MTI variants

    • Why: Can't express two-table INSERT semantics. Clear runtime error is better than invalid SQL.
    • Implementation: collection.ts — #assertNotMtiVariant
    • Tests: collection-variant.test.ts — 2 tests
  • Adds type-level write gating (create() on polymorphic base without .variant() is never)

  • Extracts shared polymorphic contract test helpers

    • Why: Eliminates 4-way duplication of contract builders.
    • Implementation: test/helpers.ts — buildMixedPolyContract, buildStiPolyContract

Compatibility / migration / risk

  • No breaking changes. All existing non-polymorphic queries, types, and tests work unchanged.
  • MTI orphan rows. A failed variant INSERT leaves an orphan base row. Transaction wrapping is deferred per spec.

Follow-ups / open questions

  • Dead tableName in mutation dispatch (F09): Minor cleanup.
  • Integration tests: Plan tasks 2.5, 3.6, 4.7 call for Postgres integration tests.
  • Transaction wrapping for MTI writes: Deferred per spec.
  • Polymorphic queries with includes: Compilation path adds MTI JOINs but no end-to-end test with include results.

Non-goals / intentionally out of scope

  • Transaction wrapping for MTI writes (deferred per spec)
  • SQL TS authoring DSL polymorphism (TML-2228)
  • Mongo ORM changes (complete in TML-2205)
  • PSL authoring changes (complete in TML-2205)
  • Discriminator-aware .where() type narrowing
  • Multi-level polymorphism (variants with sub-variants)

Summary by CodeRabbit

  • New Features

    • Polymorphic model support (STI & MTI): discriminator-aware row mapping, merged base+variant mapping, MTI join/projection support, and automatic discriminator handling on create.
  • API Changes

    • Collection and runtime APIs accept model/variant context; create/upsert/createAll inputs and mutation/query flows are polymorphism-aware and enforce MTI write constraints (two-step MTI creation).
  • Tests

    • Extensive unit, type-level and integration tests and helpers covering polymorphism resolution, mapping, MTI joins, and create/mutation behavior.

@coderabbitai

coderabbitai Bot commented Apr 9, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 52b7d358-dde1-4971-8f19-68033c3b3569

📥 Commits

Reviewing files that changed from the base of the PR and between 51ff183 and 36df00c.

📒 Files selected for processing (1)
  • packages/3-extensions/sql-orm-client/src/collection-runtime.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/3-extensions/sql-orm-client/src/collection-runtime.ts

📝 Walkthrough

Walkthrough

Adds polymorphism (STI/MTI) support across the SQL ORM: model metadata and resolver, polymorphic row mapping and MTI join/projection injection, model-name-based mapping/dispatch, variant-aware create typings and MTI create orchestration, and extensive tests/fixtures.

Changes

Cohort / File(s) Summary
Contract & Polymorphism Types
packages/3-extensions/sql-orm-client/src/collection-contract.ts, packages/3-extensions/sql-orm-client/src/types.ts
Added PolymorphismVariantInfo / PolymorphismInfo, resolvePolymorphismInfo() with caching; removed findModelNameForTable; extended collection state with variantName and added VariantCreateInput / ResolvedCreateInput type utilities.
Runtime Mapping & Internal Types
packages/3-extensions/sql-orm-client/src/collection-runtime.ts, packages/3-extensions/sql-orm-client/src/collection-internal-types.ts
Switched mapping APIs to accept modelName; added mapPolymorphicRow() and merged column→field maps (MTI namespacing); introduced WithVariantState helper type.
Dispatch, Mutation & Executor
packages/3-extensions/sql-orm-client/src/collection-dispatch.ts, packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts, packages/3-extensions/sql-orm-client/src/mutation-executor.ts
Changed dispatch/mutation option shapes to include modelName; integrated polymorphism-aware mapping into includes and mutation-return handling; exported withMutationScope.
Collection API & Orchestration
packages/3-extensions/sql-orm-client/src/collection.ts, packages/3-extensions/sql-orm-client/src/grouped-collection.ts
Made variant() preserve variant state type; create/createAll/createCount/upsert use ResolvedCreateInput; added MTI create flow (base insert then variant insert) and MTI guardrails; switched aggregate mapping to model-based mapping.
Query Planner / MTI Joins
packages/3-extensions/sql-orm-client/src/query-plan-select.ts
Added buildMtiJoins() to emit MTI JOINs and projection aliases; compileSelect / compileSelectWithIncludeStrategy accept optional modelName to inject MTI joins/projections.
Public API Surface
packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts, packages/3-extensions/sql-orm-client/src/mutation-executor.ts
Updated exported option types to use modelName; exported withMutationScope.
Tests, Fixtures & Helpers
packages/3-extensions/sql-orm-client/test/..., packages/3-extensions/sql-orm-client/test/helpers.ts
Added buildMixedPolyContract() / buildStiPolyContract() fixtures; updated tests to pass modelName; added unit and integration tests for resolvePolymorphismInfo, mapPolymorphicRow, MTI joins, STI/MTI create flows, and transactional MTI insert verification.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Collection as Collection
    participant Contract as ContractResolver
    participant QueryPlanner as QueryPlanner
    participant Database as Database
    participant Mapper as RowMapper

    Client->>Collection: all() / createAll(data) [optional variant]
    Collection->>Contract: resolvePolymorphismInfo(contract, modelName)
    Contract-->>Collection: PolymorphismInfo
    alt Read path
        Collection->>QueryPlanner: compileSelect(..., modelName)
        QueryPlanner->>Contract: resolvePolymorphismInfo(...)
        QueryPlanner->>QueryPlanner: buildMtiJoins() -> joins + projections
        QueryPlanner-->>Collection: SELECT AST
        Collection->>Database: execute SELECT
        Database-->>Collection: rows (base + variant__col aliases)
        Collection->>Mapper: mapPolymorphicRow(row, polyInfo, variantName?)
        Mapper-->>Collection: mapped model row
    else MTI create path
        Collection->>Database: INSERT base table (includes discriminator)
        Database-->>Collection: base row (with PK)
        Collection->>Database: INSERT variant table (MTI) with PK
        Database-->>Collection: variant row
        Collection->>Mapper: mapPolymorphicRow(merged base+variant, polyInfo, variant)
        Mapper-->>Collection: mapped model row
    end
    Collection-->>Client: result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Poem

🐰 I hopped through contracts, tables, and type,
I nudged discriminators into fields just right.
STI trims extras, MTI joins tables bold,
I stitch base and variant rows until they hold.
Hop, map, return — a polymorphic delight.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.32% 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 accurately describes the primary change: adding STI and MTI polymorphism runtime support to the SQL ORM client, which is the core focus of this substantial PR.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2227-sql-orm-polymorphism-runtime-sti-mti

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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

@pkg-pr-new

pkg-pr-new Bot commented Apr 9, 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@321

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@321

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

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

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

@prisma-next/runtime-executor

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-pipeline-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@321

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@321

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@321

commit: 36df00c

@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)
packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts (1)

16-25: ⚠️ Potential issue | 🟡 Minor

Remove unused tableName from both options interfaces.

The tableName field is declared but never destructured or used in dispatchMutationRows and executeMutationReturningSingleRow. Both functions use modelName for row mapping operations instead. This is dead code introduced during refactoring that should be cleaned up.

♻️ Proposed cleanup
 interface DispatchMutationRowsOptions<Row> {
   readonly contract: Contract<SqlStorage>;
   readonly runtime: CollectionContext<Contract<SqlStorage>>['runtime'];
   readonly compiled: SqlQueryPlan<Record<string, unknown>>;
-  readonly tableName: string;
   readonly modelName: string;
   readonly includes: readonly IncludeExpr[];
   readonly hiddenColumns: readonly string[];
   readonly mapRow: (mapped: Record<string, unknown>) => Row;
 }
 interface ExecuteSingleMutationOptions<Row> {
   readonly contract: Contract<SqlStorage>;
   readonly runtime: CollectionContext<Contract<SqlStorage>>['runtime'];
   readonly compiled: SqlQueryPlan<Record<string, unknown>>;
-  readonly tableName: string;
   readonly modelName: string;
   readonly includes: readonly IncludeExpr[];
   readonly hiddenColumns: readonly string[];
   readonly mapRow: (mapped: Record<string, unknown>) => Row;
   readonly onMissingRowMessage: string;
 }

Also remove tableName: assignments from callers in collection.ts (lines 732, 1025, 1092) and tests.

🤖 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/collection-mutation-dispatch.ts`
around lines 16 - 25, Remove the unused tableName property from the
DispatchMutationRowsOptions and any other options interface that declares it
(e.g., the options type consumed by dispatchMutationRows and
executeMutationReturningSingleRow), and update all call sites that pass
tableName (notably callers in collection.ts around the dispatching calls) and
related tests to stop supplying tableName; ensure all usages in functions like
dispatchMutationRows and executeMutationReturningSingleRow reference modelName
only (no destructuring of tableName), adjust types/signatures accordingly, and
run tests to confirm no remaining references to tableName.
packages/3-extensions/sql-orm-client/src/collection.ts (1)

670-678: ⚠️ Potential issue | 🔴 Critical

Propagate variant state through nested creates.

When create() takes the nested-mutation path, .variant() context is dropped entirely. That means STI creates skip discriminator injection, and MTI creates never perform the variant-table insert. This path needs to call the variant-aware create flow or reject variant+nested create until it is implemented.

🤖 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/collection.ts` around lines 670 -
678, The nested-create branch drops any variant context causing STI/MTI to
misbehave; before calling executeNestedCreateMutation, detect whether a variant
has been set on this collection (e.g., via the collection's variant context /
this.ctx.variant or the variant() call) and either (A) route the call into the
variant-aware create flow used by the non-nested path so
discriminator/table-insert logic runs, or (B) explicitly reject the combination
by throwing a clear error when a variant is present and nested creates exist.
Update the if-block that checks hasNestedMutationCallbacks(this.contract,
this.modelName, data) to perform this variant check and choose the appropriate
behavior (call the variant-aware create path or throw), referencing
executeNestedCreateMutation, hasNestedMutationCallbacks, create()/variant() and
this.modelName to locate and implement the change.
🧹 Nitpick comments (2)
packages/3-extensions/sql-orm-client/test/helpers.ts (1)

57-58: Use getTestContract() directly here.

The JSON round-trip is redundant and lossy: getTestContract() already returns a deep clone, while JSON.stringify() will silently strip any future non-JSON contract values from these fixtures.

♻️ Suggested cleanup
 export function buildMixedPolyContract(): TestContract {
-  const raw = JSON.parse(JSON.stringify(getTestContract()));
+  const raw = getTestContract();
@@
 export function buildStiPolyContract(): TestContract {
-  const raw = JSON.parse(JSON.stringify(getTestContract()));
+  const raw = getTestContract();

Based on learnings, prefer well-established or native deep-cloning utilities over custom JSON round-trips for deep cloning in this repo.

Also applies to: 122-123

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-extensions/sql-orm-client/test/helpers.ts` around lines 57 - 58,
The JSON stringify/parse round-trip in buildMixedPolyContract is redundant and
lossy—replace the JSON deep-clone with a direct call to getTestContract() (use
getTestContract() as the source for raw contract data) so buildMixedPolyContract
returns or operates on the already-cloned fixture; similarly remove other JSON
round-trips around getTestContract() (e.g., the instances referenced at lines
122-123) to avoid stripping non-JSON values.
packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts (1)

71-81: Same consideration for ExecuteSingleMutationOptions.

The tableName field is also unused in executeMutationReturningSingleRow (line 86-95 destructures modelName but not tableName).

🤖 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/collection-mutation-dispatch.ts`
around lines 71 - 81, The ExecuteSingleMutationOptions interface includes a
tableName property that is not used by executeMutationReturningSingleRow (the
function destructures modelName but not tableName); remove tableName from
ExecuteSingleMutationOptions or add tableName to the destructuring in
executeMutationReturningSingleRow so the interface matches usage—update the
ExecuteSingleMutationOptions declaration or the
executeMutationReturningSingleRow parameter destructure to keep only required
fields (e.g., modelName) or include tableName where needed to avoid the unused
property.
🤖 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/3-extensions/sql-orm-client/src/collection-contract.ts`:
- Around line 75-91: The loop over model.variants currently treats a missing
variant model as present by falling back to baseTable; instead, in the iteration
over model.variants (the block using variantModelName, variantEntry,
variantModel, baseTable, variants, variantsByValue, mtiVariants), check that
const variantModel = models[variantModelName] exists and if not immediately
throw a descriptive Error (including variantModelName and the parent model name)
so the contract construction fails fast; only compute variantTable and strategy
after validating variantModel (do not silently use baseTable when variantModel
is missing) and then continue populating variants, variantsByValue, and
mtiVariants as before.

In `@packages/3-extensions/sql-orm-client/src/collection-runtime.ts`:
- Around line 91-152: The mapping code in mapPolymorphicRow drops
identity-mapped columns because it only assigns when the column key exists in
the maps from getColumnToFieldMap / getMergedColumnToFieldMap; change both
branches so they compute the target field name as map[col] ?? col (i.e., fall
back to the column name when no explicit remap exists) and assign
mapped[targetField] = val for each entry; update the base branch (using baseMap)
and the variant branch (using mergedMap) accordingly in mapPolymorphicRow so
identity-mapped columns are preserved (refer to getColumnToFieldMap,
getMergedColumnToFieldMap, and mapPolymorphicRow).

In `@packages/3-extensions/sql-orm-client/src/collection.ts`:
- Around line 772-848: `#executeMtiCreate` currently constructs the yielded row
from the local variantRow (and baseCreated) instead of using the actual INSERT
... RETURNING payload and the collection's normal mutation shaping pipeline,
which bypasses .select()/.include() handling and hidden-column stripping; fix it
by reading the variant INSERT RETURNING result (use executeQueryPlan(runtime,
variantCompiled).toArray() and grab variantCreated like you do for baseCreated),
use the returned variantCreated values when building prefixedVariant (not
variantRow), then pass the merged DB row through the same post-insert shaping
used elsewhere (i.e., the collection's normal result shaping/post-processing
utilities) rather than hand-building the final object — keep references to
applyCreateDefaults, compileInsertReturning, executeQueryPlan, mapPolymorphicRow
and ensure the shaped/returned row respects .select()/.include() and hides
internal columns before yielding.

---

Outside diff comments:
In `@packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts`:
- Around line 16-25: Remove the unused tableName property from the
DispatchMutationRowsOptions and any other options interface that declares it
(e.g., the options type consumed by dispatchMutationRows and
executeMutationReturningSingleRow), and update all call sites that pass
tableName (notably callers in collection.ts around the dispatching calls) and
related tests to stop supplying tableName; ensure all usages in functions like
dispatchMutationRows and executeMutationReturningSingleRow reference modelName
only (no destructuring of tableName), adjust types/signatures accordingly, and
run tests to confirm no remaining references to tableName.

In `@packages/3-extensions/sql-orm-client/src/collection.ts`:
- Around line 670-678: The nested-create branch drops any variant context
causing STI/MTI to misbehave; before calling executeNestedCreateMutation, detect
whether a variant has been set on this collection (e.g., via the collection's
variant context / this.ctx.variant or the variant() call) and either (A) route
the call into the variant-aware create flow used by the non-nested path so
discriminator/table-insert logic runs, or (B) explicitly reject the combination
by throwing a clear error when a variant is present and nested creates exist.
Update the if-block that checks hasNestedMutationCallbacks(this.contract,
this.modelName, data) to perform this variant check and choose the appropriate
behavior (call the variant-aware create path or throw), referencing
executeNestedCreateMutation, hasNestedMutationCallbacks, create()/variant() and
this.modelName to locate and implement the change.

---

Nitpick comments:
In `@packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts`:
- Around line 71-81: The ExecuteSingleMutationOptions interface includes a
tableName property that is not used by executeMutationReturningSingleRow (the
function destructures modelName but not tableName); remove tableName from
ExecuteSingleMutationOptions or add tableName to the destructuring in
executeMutationReturningSingleRow so the interface matches usage—update the
ExecuteSingleMutationOptions declaration or the
executeMutationReturningSingleRow parameter destructure to keep only required
fields (e.g., modelName) or include tableName where needed to avoid the unused
property.

In `@packages/3-extensions/sql-orm-client/test/helpers.ts`:
- Around line 57-58: The JSON stringify/parse round-trip in
buildMixedPolyContract is redundant and lossy—replace the JSON deep-clone with a
direct call to getTestContract() (use getTestContract() as the source for raw
contract data) so buildMixedPolyContract returns or operates on the
already-cloned fixture; similarly remove other JSON round-trips around
getTestContract() (e.g., the instances referenced at lines 122-123) to avoid
stripping non-JSON values.
🪄 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: ef1e70c2-02b7-4d87-b61f-e29624ca8ab8

📥 Commits

Reviewing files that changed from the base of the PR and between 00751a0 and c73c769.

⛔ Files ignored due to path filters (2)
  • projects/orm-consolidation/plans/sql-orm-polymorphism-runtime-plan.md is excluded by !projects/**
  • projects/orm-consolidation/specs/sql-orm-polymorphism-runtime.spec.md is excluded by !projects/**
📒 Files selected for processing (18)
  • packages/3-extensions/sql-orm-client/src/collection-contract.ts
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-internal-types.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-runtime.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/grouped-collection.ts
  • packages/3-extensions/sql-orm-client/src/mutation-executor.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-select.ts
  • packages/3-extensions/sql-orm-client/src/types.ts
  • packages/3-extensions/sql-orm-client/test/collection-contract.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-runtime.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-variant.test.ts
  • packages/3-extensions/sql-orm-client/test/helpers.ts
  • packages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-select.test.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.

🧹 Nitpick comments (2)
packages/3-extensions/sql-orm-client/src/collection-runtime.ts (2)

97-97: Cache key should include variantTable for correctness.

The cache key omits variantTable, but the merged map differs based on whether MTI table-prefixing is applied (lines 111-115). While current usage derives variantTable consistently from the variant's strategy, the cache could return stale results if calling conventions change.

🛡️ Suggested fix
-  const cacheKey = `${baseModelName}:${variantModelName}`;
+  const cacheKey = `${baseModelName}:${variantModelName}:${variantTable ?? ''}`;
🤖 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/collection-runtime.ts` at line 97,
The cache key currently built as cacheKey =
`${baseModelName}:${variantModelName}` omits variantTable, causing incorrect
cache hits when MTI table-prefixing changes; update the key construction in
collection-runtime.ts to include the variantTable value used when merging maps
(the logic around the merged map at the code that references variantTable and
the MTI strategy) so cached entries are unique per baseModelName,
variantModelName, and variantTable.

129-131: Consider adding a type guard for the discriminator value.

The as string cast on line 131 assumes the discriminator column always contains a string. If it's null or another type, the lookup silently returns undefined and falls back to base-only mapping, which may hide data issues.

🛡️ Suggested defensive check
-  const variant = variantName
-    ? polyInfo.variants.get(variantName)
-    : polyInfo.variantsByValue.get(row[polyInfo.discriminatorColumn] as string);
+  const discriminatorValue = row[polyInfo.discriminatorColumn];
+  const variant = variantName
+    ? polyInfo.variants.get(variantName)
+    : typeof discriminatorValue === 'string'
+      ? polyInfo.variantsByValue.get(discriminatorValue)
+      : undefined;
🤖 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/collection-runtime.ts` around lines
129 - 131, Add a defensive type guard around the discriminator lookup so we
don't blindly cast row[polyInfo.discriminatorColumn] to string; check that
row[polyInfo.discriminatorColumn] is a non-null string (or coerce/validate it)
before calling polyInfo.variantsByValue.get(...). Update the variant assignment
in the block that uses variantName, polyInfo, variants, variantsByValue,
discriminatorColumn, and row to: if variantName use
polyInfo.variants.get(variantName) else validate the discriminator value is a
string and only then call polyInfo.variantsByValue.get(value); otherwise handle
the invalid/missing discriminator explicitly (e.g., set variant = undefined or
log/throw) so silent falls-back cannot hide data issues.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/3-extensions/sql-orm-client/src/collection-runtime.ts`:
- Line 97: The cache key currently built as cacheKey =
`${baseModelName}:${variantModelName}` omits variantTable, causing incorrect
cache hits when MTI table-prefixing changes; update the key construction in
collection-runtime.ts to include the variantTable value used when merging maps
(the logic around the merged map at the code that references variantTable and
the MTI strategy) so cached entries are unique per baseModelName,
variantModelName, and variantTable.
- Around line 129-131: Add a defensive type guard around the discriminator
lookup so we don't blindly cast row[polyInfo.discriminatorColumn] to string;
check that row[polyInfo.discriminatorColumn] is a non-null string (or
coerce/validate it) before calling polyInfo.variantsByValue.get(...). Update the
variant assignment in the block that uses variantName, polyInfo, variants,
variantsByValue, discriminatorColumn, and row to: if variantName use
polyInfo.variants.get(variantName) else validate the discriminator value is a
string and only then call polyInfo.variantsByValue.get(value); otherwise handle
the invalid/missing discriminator explicitly (e.g., set variant = undefined or
log/throw) so silent falls-back cannot hide data issues.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 0756b2ad-a208-4629-9060-046c38b5a48c

📥 Commits

Reviewing files that changed from the base of the PR and between c73c769 and 8ec688c.

📒 Files selected for processing (4)
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-runtime.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/3-extensions/sql-orm-client/src/collection.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts

wmadden added 23 commits April 9, 2026 16:49
Design decisions for STI/MTI query compilation, model-first row
mapping, variant-aware writes, and PolymorphismInfo strategy resolution.
Scoped to the SQL runtime work from the parent polymorphism spec.
…ification

Introduce PolymorphismInfo structure that classifies each variant as STI
(same table) or MTI (different table) from storage mappings. Cached per
(contract, modelName) via WeakMap. Foundation for polymorphic query
compilation and result mapping.
Add modelName parameter to dispatchCollectionRows, dispatchMutationRows,
executeMutationReturningSingleRow, mapStorageRowToModelFields,
createRowEnvelope, and stripHiddenMappedFields. When provided, skips
findModelNameForTable reverse lookup. Backward-compatible: existing
callers without modelName use the original table-based resolution.
… result mapping

Maps storage rows to model fields using per-variant column-to-field maps.
For each row, reads the discriminator value, looks up the variant, merges
base + variant column maps, and strips columns not in the merged map.
Falls back to base-only mapping for unknown discriminator values. Wired
into dispatchCollectionRows and include paths.
Verify full Collection -> dispatch -> mapPolymorphicRow pipeline for STI
models: base query maps mixed-variant rows into variant-specific shapes
(strips other variants NULL columns), variant query maps with narrowed
shape.
… queries

When compiling SELECT for a polymorphic base model with MTI variants,
automatically add LEFT JOINs (base query) or INNER JOINs (variant query)
for each MTI variant table, projecting non-PK variant columns. STI-only
variants produce no JOINs since all columns are on the shared table.
Verify the full Collection pipeline with Bug (STI, same table) and
Feature (MTI, separate table) variants: base query maps both variant
types to correct shapes, variant queries narrow to single variant.
…injection

When creating rows via .variant(V).createAll(), resolves PolymorphismInfo,
merges base + variant field-to-column maps, and injects the discriminator
column/value. Also applies to createCount(). Non-variant creates are
unchanged.
…ation

For MTI variants, createAll() now orchestrates two sequential INSERTs:
1. Base table INSERT with discriminator value, returning the shared PK
2. Variant table INSERT with the shared PK and variant-specific fields
Results are mapped through mapPolymorphicRow for consistent output.
CreateInput for polymorphic base models (with discriminator+variants) now
resolves to never, enforcing that writes go through .variant() first.
VariantCreateInput combines base + variant fields minus discriminator.
CollectionTypeState tracks variantName to thread through create signatures.
MTI variants require multi-table orchestration that createCount and upsert
do not implement. Both now throw a descriptive error directing users to
createAll() instead. Addresses review findings F01 and F03.
The alias was a leftover from an earlier iteration. Use the variantName
parameter directly. Addresses review finding F02.
compileSelectWithIncludeStrategy now accepts modelName and injects MTI
LEFT/INNER JOINs alongside include JOINs. Previously, polymorphic queries
with includes would omit MTI variant columns from the result set.
Addresses review finding F04.
…s, remove findModelNameForTable

The model-first mapping refactor is completed: modelName is now a required
parameter in mapStorageRowToModelFields, stripHiddenMappedFields, and
createRowEnvelope. The findModelNameForTable reverse-lookup (which is
fundamentally broken for STI where multiple models share a table) is removed
along with its cache. All call sites already passed modelName explicitly.
Deduplicate the polymorphic contract builders that were duplicated across four
test files. buildMixedPolyContract() (Task/Bug STI + Feature MTI) and
buildStiPolyContract() (User/Admin/Regular STI) are now shared from helpers.ts.
…refix

MTI variant columns are now projected as ${table}__${col} (e.g.
features__priority) to prevent silent collisions when multiple MTI variant
tables have columns with the same name. The merged column-to-field map and
the MTI create path are updated to use these prefixed keys consistently.
…eate

applyCreateDefaults was only called for the base table row in MTI writes.
Variant table columns with client-side defaults (e.g. timestamps) were not
receiving their default values. Now both base and variant rows get defaults
applied before their respective INSERTs.
…h interfaces

tableName was no longer used after the model-first refactor but remained in
DispatchMutationRowsOptions and ExecuteSingleMutationOptions interfaces and
all their call sites. Removed from interfaces, callers, and tests.
Replace col-in-map guard + non-null assertion with undefined check on a
local variable, satisfying the noNonNullAssertion lint rule.
…cope

Both INSERTs (base + variant) now execute within withMutationScope,
which uses runtime.transaction() when available. This prevents orphan
base rows if the variant INSERT fails.
Rewrites MTI JOIN tests to use expect(plan.ast).toEqual(...) with
the full expected SelectAst instead of checking individual properties.
This makes absence-of-JOINs tests less brittle and the positive tests
more readable.
Covers end-to-end STI + MTI behavior against a real Postgres database:
- Base query returns all variants with discriminator-aware result mapping
- variant(Bug) filters STI rows
- variant(Feature) INNER JOINs and returns MTI rows
- STI create auto-injects discriminator
- MTI create inserts into both tables (base + variant)
Records triaged action items from @aqrln review comments:
- R01: Missing Postgres integration tests (accept)
- R02: MTI writes need transaction wrapping (accept)
- R03: MTI JOIN tests need full AST assertions (accept)
wmadden added 2 commits April 9, 2026 16:49
- Guard against missing variant models in resolvePolymorphismInfo (throw
  instead of silently falling back to baseTable)
- Preserve identity-mapped columns in mapPolymorphicRow by introducing
  getCompleteColumnToFieldMap that includes fields without explicit column
  mappings
- Use variant INSERT RETURNING result in MTI create instead of the input
  row, so server-generated values are preserved
- Route upsert create values through #mapCreateRows so STI discriminator
  and variant fields are correctly injected
@wmadden
wmadden force-pushed the tml-2227-sql-orm-polymorphism-runtime-sti-mti branch from f458513 to 51ff183 Compare April 9, 2026 18:31

@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

🧹 Nitpick comments (1)
packages/3-extensions/sql-orm-client/test/helpers.ts (1)

57-58: Consider using structuredClone for consistency.

Both buildMixedPolyContract() and buildStiPolyContract() use JSON.parse(JSON.stringify(...)) for cloning, while getTestContract() (line 25) already uses structuredClone. Using structuredClone is more efficient and idiomatic.

♻️ Suggested refactor
 export function buildMixedPolyContract(): TestContract {
-  const raw = JSON.parse(JSON.stringify(getTestContract()));
+  const raw = structuredClone(getTestContract());
 export function buildStiPolyContract(): TestContract {
-  const raw = JSON.parse(JSON.stringify(getTestContract()));
+  const raw = structuredClone(getTestContract());

Also applies to: 122-123

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-extensions/sql-orm-client/test/helpers.ts` around lines 57 - 58,
Replace the JSON.parse(JSON.stringify(...)) clones in buildMixedPolyContract()
and buildStiPolyContract() with structuredClone(getTestContract()) to match
getTestContract()'s approach; update both functions to call structuredClone on
the returned test contract (and then modify the clone as needed) so cloning is
more efficient and consistent across these helpers.
🤖 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/3-extensions/sql-orm-client/src/collection-runtime.ts`:
- Line 98: The cache key for column mappings uses only baseModelName and
variantModelName (cacheKey = `${baseModelName}:${variantModelName}`) which can
collide when the same variantName is used with different variantTable values;
update the cache key to include variantTable as well (e.g., include variantTable
alongside baseModelName and variantModelName) so entries are unique per
table/variant context and prevent returning incorrect cached mappings from
functions that compute column maps in collection-runtime.ts.

---

Nitpick comments:
In `@packages/3-extensions/sql-orm-client/test/helpers.ts`:
- Around line 57-58: Replace the JSON.parse(JSON.stringify(...)) clones in
buildMixedPolyContract() and buildStiPolyContract() with
structuredClone(getTestContract()) to match getTestContract()'s approach; update
both functions to call structuredClone on the returned test contract (and then
modify the clone as needed) so cloning is more efficient and consistent across
these helpers.
🪄 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: 42f23360-1e39-4114-888d-ec7d39b776f6

📥 Commits

Reviewing files that changed from the base of the PR and between f458513 and 51ff183.

⛔ Files ignored due to path filters (3)
  • projects/orm-consolidation/plans/sql-orm-polymorphism-runtime-plan.md is excluded by !projects/**
  • projects/orm-consolidation/specs/reviews/code-review.md is excluded by !projects/**
  • projects/orm-consolidation/specs/sql-orm-polymorphism-runtime.spec.md is excluded by !projects/**
📒 Files selected for processing (19)
  • packages/3-extensions/sql-orm-client/src/collection-contract.ts
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-internal-types.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-runtime.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/grouped-collection.ts
  • packages/3-extensions/sql-orm-client/src/mutation-executor.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-select.ts
  • packages/3-extensions/sql-orm-client/src/types.ts
  • packages/3-extensions/sql-orm-client/test/collection-contract.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-runtime.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-variant.test.ts
  • packages/3-extensions/sql-orm-client/test/helpers.ts
  • packages/3-extensions/sql-orm-client/test/integration/polymorphism.test.ts
  • packages/3-extensions/sql-orm-client/test/polymorphism.test-d.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • packages/3-extensions/sql-orm-client/src/collection-internal-types.ts
  • packages/3-extensions/sql-orm-client/src/grouped-collection.ts
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/test/collection-contract.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/polymorphism.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-runtime.test.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts

Ensures cache correctness by capturing all inputs to getMergedColumnToFieldMap
in the cache key, preventing theoretical collisions between STI and MTI
contexts for the same variant.
@wmadden
wmadden merged commit 88c204e into main Apr 10, 2026
15 checks passed
@wmadden
wmadden deleted the tml-2227-sql-orm-polymorphism-runtime-sti-mti branch April 10, 2026 05:24
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.

2 participants