Repository navigation
feat(sql-orm-client): add STI and MTI polymorphism runtime - #321
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Comment |
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/runtime-executor
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-emitter
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-pipeline-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts (1)
16-25:⚠️ Potential issue | 🟡 MinorRemove unused
tableNamefrom both options interfaces.The
tableNamefield is declared but never destructured or used indispatchMutationRowsandexecuteMutationReturningSingleRow. Both functions usemodelNamefor 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 incollection.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 | 🔴 CriticalPropagate 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: UsegetTestContract()directly here.The JSON round-trip is redundant and lossy:
getTestContract()already returns a deep clone, whileJSON.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 forExecuteSingleMutationOptions.The
tableNamefield is also unused inexecuteMutationReturningSingleRow(line 86-95 destructuresmodelNamebut nottableName).🤖 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
⛔ Files ignored due to path filters (2)
projects/orm-consolidation/plans/sql-orm-polymorphism-runtime-plan.mdis excluded by!projects/**projects/orm-consolidation/specs/sql-orm-polymorphism-runtime.spec.mdis excluded by!projects/**
📒 Files selected for processing (18)
packages/3-extensions/sql-orm-client/src/collection-contract.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/collection-internal-types.tspackages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.tspackages/3-extensions/sql-orm-client/src/collection-runtime.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/grouped-collection.tspackages/3-extensions/sql-orm-client/src/mutation-executor.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/collection-contract.test.tspackages/3-extensions/sql-orm-client/test/collection-dispatch.test.tspackages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.tspackages/3-extensions/sql-orm-client/test/collection-runtime.test.tspackages/3-extensions/sql-orm-client/test/collection-variant.test.tspackages/3-extensions/sql-orm-client/test/helpers.tspackages/3-extensions/sql-orm-client/test/polymorphism.test-d.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
packages/3-extensions/sql-orm-client/src/collection-runtime.ts (2)
97-97: Cache key should includevariantTablefor 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 derivesvariantTableconsistently 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 stringcast on line 131 assumes the discriminator column always contains a string. If it'snullor another type, the lookup silently returnsundefinedand 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
📒 Files selected for processing (4)
packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.tspackages/3-extensions/sql-orm-client/src/collection-runtime.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/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
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)
- 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
f458513 to
51ff183
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/3-extensions/sql-orm-client/test/helpers.ts (1)
57-58: Consider usingstructuredClonefor consistency.Both
buildMixedPolyContract()andbuildStiPolyContract()useJSON.parse(JSON.stringify(...))for cloning, whilegetTestContract()(line 25) already usesstructuredClone. UsingstructuredCloneis 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
⛔ Files ignored due to path filters (3)
projects/orm-consolidation/plans/sql-orm-polymorphism-runtime-plan.mdis excluded by!projects/**projects/orm-consolidation/specs/reviews/code-review.mdis excluded by!projects/**projects/orm-consolidation/specs/sql-orm-polymorphism-runtime.spec.mdis excluded by!projects/**
📒 Files selected for processing (19)
packages/3-extensions/sql-orm-client/src/collection-contract.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/collection-internal-types.tspackages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.tspackages/3-extensions/sql-orm-client/src/collection-runtime.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/grouped-collection.tspackages/3-extensions/sql-orm-client/src/mutation-executor.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/collection-contract.test.tspackages/3-extensions/sql-orm-client/test/collection-dispatch.test.tspackages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.tspackages/3-extensions/sql-orm-client/test/collection-runtime.test.tspackages/3-extensions/sql-orm-client/test/collection-variant.test.tspackages/3-extensions/sql-orm-client/test/helpers.tspackages/3-extensions/sql-orm-client/test/integration/polymorphism.test.tspackages/3-extensions/sql-orm-client/test/polymorphism.test-d.tspackages/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.
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
PolymorphismInfo,resolvePolymorphismInfo.findModelNameForTableremoved.mapPolymorphicRow,getMergedColumnToFieldMap.modelNamerequired in all mapping functions.modelNamethreading. MTI JOINs in single-query include path.buildMtiJoins,compileSelectandcompileSelectWithIncludeStrategywith MTI support.#assertNotMtiVariantguards forcreateCount/upsert.VariantCreateInput,ResolvedCreateInput.WithVariantState.modelNamethreading.modelNameused directly in mapping.modelNameused directly in mapping.The story
Introduce strategy resolution.
resolvePolymorphismInforeads a base model'sdiscriminatorandvariantsmetadata from the contract. For each variant, it compares the variant'sstorage.tableto the base's — same table means STI, different table means MTI. The result is a cachedPolymorphismInfostructure withstrategy: 'sti' | 'mti'per variant.Refactor mapping to be model-first. The existing dispatch/mapping path threaded
tableNameand usedfindModelNameForTableto reverse-lookup the model. This breaks under STI where multiple models share a table. The refactor makesmodelNamerequired inmapStorageRowToModelFields,stripHiddenMappedFields,createRowEnvelope, and all dispatch/mutation-dispatch functions.findModelNameForTableis removed entirely.Add discriminator-aware result mapping.
mapPolymorphicRowinspects 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.Compile MTI JOINs with table-qualified aliases.
buildMtiJoinsgenerates 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 bothcompileSelectandcompileSelectWithIncludeStrategy.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, callsapplyCreateDefaultson both tables, then executes a variant INSERT. The returned merged row uses table-prefixed keys formapPolymorphicRow.Guard MTI-incompatible mutations.
createCountandupsertthrow at runtime for MTI variants via#assertNotMtiVariant.Gate writes behind
.variant()at the type level.ResolvedCreateInputresolves toneverfor polymorphic bases without a variant name, makingcreate()on a bare polymorphic collection a compile-time error.Extract shared test helpers.
buildMixedPolyContract()andbuildStiPolyContract()consolidated intotest/helpers.ts, eliminating duplication across four test files.Behavior changes & evidence
Adds
PolymorphismInfostrategy resolution (STI vs MTI from storage table comparison)resolvePolymorphismInfoRemoves
findModelNameForTable, makesmodelNamerequired in all mapping functionsmodelNameeliminates ambiguity.modelNameAdds
mapPolymorphicRow()with table-qualified MTI alias resolutionmapPolymorphicRow,getMergedColumnToFieldMapAdds MTI JOIN compilation with
${table}__${col}aliases in both standalone and include pathsbuildMtiJoins, used incompileSelectandcompileSelectWithIncludeStrategyfeatures__priority)Adds STI variant write with discriminator auto-injection
#mapCreateRowsAdds MTI variant write with two-INSERT orchestration and defaults on both tables
applyCreateDefaultson both ensures variant table defaults are applied.#executeMtiCreateGuards
createCountandupsertagainst MTI variants#assertNotMtiVariantAdds type-level write gating (
create()on polymorphic base without.variant()isnever)ResolvedCreateInput; collection-internal-types.ts —WithVariantStateExtracts shared polymorphic contract test helpers
buildMixedPolyContract,buildStiPolyContractCompatibility / migration / risk
Follow-ups / open questions
tableNamein mutation dispatch (F09): Minor cleanup.Non-goals / intentionally out of scope
.where()type narrowingSummary by CodeRabbit
New Features
API Changes
Tests