Skip to content

Auto-created STI discriminator index is silently dropped when the entity has an embedded column #12840

Closed

Description

@brmk

Issue description

The index TypeORM auto-creates on a single-table-inheritance discriminator column is silently dropped when the STI base entity has at least one embedded column and at least one generated column.

Expected Behavior

An STI base entity declared with @TableInheritance() gets an index on its discriminator column, as EntityMetadataBuilder.createKeysForTableInheritance() intends, regardless of whether the entity also has embedded columns.

Actual Behavior

With an embedded column (@Column(() => Something)) present alongside a generated column (e.g. @PrimaryGeneratedColumn()), the discriminator index is missing from EntityMetadata.indices and is therefore never created in the schema. No error and no warning is emitted — synchronize/migration generation simply produces a table without that index.

Root cause is an array-identity subtlety in src/metadata-builder/EntityMetadataBuilder.ts.

computeEntityMetadataStep2() derives indices from ownIndices:

entityMetadata.indices = entityMetadata.embeddeds.reduce(
    (indices, embedded) => indices.concat(embedded.indicesFromTree),
    entityMetadata.ownIndices,
)
  • With zero embeddeds, Array.prototype.reduce with an initial value and an empty array returns the initial value by reference, so indices is ownIndices.
  • With one or more embeddeds, concat produces a new array, so indices is a copy that is no longer connected to ownIndices.

Later in build(), createKeysForTableInheritance() pushes the auto index onto entityMetadata.indices:

entityMetadata.indices.push(
    new IndexMetadata({ entityMetadata, columns: [entityMetadata.discriminatorColumn!], ... }),
)

In the zero-embedded case that push also lands in ownIndices (same array), so it survives. In the embedded case it lands only on the detached copy.

build() then re-runs computeEntityMetadataStep2() for every entity that has a generated column:

if (generated) {
    ...
    column.build(this.dataSource)
    this.computeEntityMetadataStep2(entityMetadata)
}

That re-run reassigns indices from ownIndices + embedded indices, and the auto-created discriminator index is discarded.

So the bug needs all three of: STI base, ≥1 embedded column, ≥1 generated column. A @PrimaryGeneratedColumn() id — which nearly every entity has — supplies the third.

An explicit @Index() on the discriminator column is unaffected: it comes from metadata args into ownIndices, so it is recreated by every step-2 run. That is also why the existing dedup guard in createKeysForTableInheritance() (isDiscriminatorColumnAlreadyIndexed) still behaves correctly once the underlying bug is fixed — no double index for users who already added the decorator by hand.

Steps to reproduce

Minimal reproduction (better-sqlite3, in-memory — the outcome is decided at the metadata layer, so every driver is affected):

import "reflect-metadata"
import {
    ChildEntity, Column, DataSource, Entity,
    PrimaryGeneratedColumn, TableInheritance,
} from "typeorm"

class Meta {
    @Column({ type: String, nullable: true })
    note?: string
}

@Entity({ name: "with_embedded" })
@TableInheritance({ column: { type: String, name: "discriminator" } })
class WithEmbedded {
    @PrimaryGeneratedColumn()
    id!: number

    @Column(() => Meta)
    meta!: Meta
}

@ChildEntity()
class WithEmbeddedChild extends WithEmbedded {}

@Entity({ name: "without_embedded" })
@TableInheritance({ column: { type: String, name: "discriminator" } })
class WithoutEmbedded {
    @PrimaryGeneratedColumn()
    id!: number
}

@ChildEntity()
class WithoutEmbeddedChild extends WithoutEmbedded {}

const ds = new DataSource({
    type: "better-sqlite3",
    database: ":memory:",
    entities: [WithEmbedded, WithEmbeddedChild, WithoutEmbedded, WithoutEmbeddedChild],
    synchronize: true,
})

await ds.initialize()

for (const target of [WithEmbedded, WithoutEmbedded]) {
    const metadata = ds.getMetadata(target)
    const indices = metadata.indices.filter(
        (index) =>
            index.columns.length === 1 &&
            index.columns[0].databaseName === "discriminator",
    )
    console.log(metadata.tableName, "discriminator indices:", indices.length)
}

Output on master (ac41823b9, 1.1.1):

with_embedded discriminator indices: 0
without_embedded discriminator indices: 1

Inspecting the created tables through a query runner gives the same result: the with_embedded table has no index on discriminator.

Removing the @Column(() => Meta) line makes the index appear. Removing @PrimaryGeneratedColumn() (using a plain primary column instead) also makes it appear, because nothing then triggers the second computeEntityMetadataStep2() run.

My Environment

Dependency Version
Operating System macOS 15 (also Linux CI)
Node.js version 24.14.1
Typescript version 5.9.3
TypeORM version master ac41823b9 (1.1.1), also 1.0.x and 0.3.x

Affected on both active branches: the code shape is identical on master and on v0 (entityMetadata.indices = entityMetadata.embeddeds.reduce(...) plus the post-hoc push in createKeysForTableInheritance). Verified reproducing on 0.3.28 and on 1.1.0 as well as current master.

Additional Context

This is not a theoretical edge case. Any framework that adds an embedded column to a base entity hits it for every STI hierarchy it defines.

Vendure is the clearest example: every Vendure entity carries an embedded customFields column and a generated id, so all of its STI discriminator indexes are missing in every Vendure installation — history_entry.discriminator, session.type, region.discriminator, stock_movement.discriminator.

The production consequence on our own installation: a history_entry table of roughly 2M rows, with admin COUNT queries filtered by discriminator sequentially scanning it under peak load. Reported downstream as vendurehq/vendure#5286, with a workaround (explicit @Index() decorators on those discriminator columns) proposed in vendurehq/vendure#5287 — but the missing index originates here, and affects any application with this entity shape.

The fix looks small: make the auto-created index land in ownIndices (which every computeEntityMetadataStep2() run preserves) instead of in the derived indices array. I have a patch and tests and will open a PR against master.

Relevant Database Driver(s)

All drivers — the index is dropped at the metadata layer, before any driver is involved.

Are you willing to resolve this issue by submitting a Pull Request?

Yes, I have the time, and I know how to start.

Activity

  1. added a commit that references this issue on Sep 5, 2026
    61b02c7
  2. webdevsamran commented on Sep 6, 2026

    @webdevsamran

    Hi team, I would like to work on this STI discriminator index bug.

    In EntityMetadataBuilder.createKeysForTableInheritance(), the discriminator index created for @TableInheritance() entities is inadvertently skipped when the entity contains embedded or generated columns. I can ensure the table inheritance discriminator index is consistently registered regardless of embedded columns, and add regression tests in test/github-issues/.

    Could you please assign this to me? Thanks!

  3. brmk commented on Sep 6, 2026

    @brmk
    ContributorAuthor

    @webdevsamran There is already a pull request: #12841

  4. added a commit that references this issue on Sep 8, 2026
    cd5d8a7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions