Skip to content

deepValue() throws when find options omit an embedded that holds an eager relation #12774

Closed

Description

@michaelbromley

Issue description

A query with relationLoadStrategy: 'query' throws TypeError: Cannot read properties of undefined when the entity has an eager relation declared inside an embedded, and the find options name some other relation without mentioning the embedded.

Expected behaviour

The query returns the entities with the eager relation loaded, the same as it does when no find options are passed.

Actual behaviour

TypeError: Cannot read properties of undefined (reading 'owner')

Steps to reproduce

import 'reflect-metadata';
import { Column, DataSource, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
class User {
    @PrimaryGeneratedColumn() id: number;
    @Column() name: string;
}

@Entity()
class Image {
    @PrimaryGeneratedColumn() id: number;
    @Column() url: string;
}

class Meta {
    @ManyToOne(() => User, { eager: true, nullable: true })
    owner: User | null;
}

@Entity()
class Post {
    @PrimaryGeneratedColumn() id: number;
    @Column() title: string;
    @ManyToOne(() => Image, { nullable: true }) image: Image | null;
    @Column(() => Meta) meta: Meta;
}

async function main() {
    const dataSource = new DataSource({
        type: 'better-sqlite3',
        database: ':memory:',
        entities: [User, Image, Post],
        synchronize: true,
    });
    await dataSource.initialize();

    const user = await dataSource.getRepository(User).save({ name: 'Ann' });
    const image = await dataSource.getRepository(Image).save({ url: 'a.png' });
    await dataSource.getRepository(Post).save({ title: 'Hello', image, meta: { owner: user } });

    // The find options name `image`, and say nothing about the `meta` embedded which holds the
    // eager `owner` relation.
    const posts = await dataSource.getRepository(Post).find({
        relationLoadStrategy: 'query',
        relations: { image: true },
    });
    console.log('loaded', posts.length, 'post(s), owner =', posts[0].meta.owner?.name);
    await dataSource.destroy();
}

main().catch(e => {
    console.error(`${e.constructor.name}: ${e.message}`);
    process.exit(1);
});

On 1.1.0 this prints TypeError: Cannot read properties of undefined (reading 'owner'). On 0.3.31 it prints loaded 1 post(s), owner = Ann.

Cause

OrmUtils.deepValue() walks a dotted property path segment by segment without checking that the previous segment resolved to anything:

static deepValue(obj, path) {
    const segments = path.split(".")
    for (let i = 0, len = segments.length; i < len; i++) {
        obj = obj[segments[i]]
    }
    return obj
}

SelectQueryBuilder calls it in seven places to narrow select, order and relations down to the part that applies to a single relation. All seven treat a missing path as "nothing specified for this relation". The call that brings the throw into an ordinary query is the one in the query-strategy branch of executeEntitiesAndRawResults(), which runs for every eager relation of the queried entity whenever find options are set:

relations: this.findOptions.relations
    ? OrmUtils.deepValue(this.findOptions.relations, relation.propertyPath)
    : undefined,

For a relation declared inside an embedded, relation.propertyPath is meta.owner. Find options of { image: true } have no meta key, so the loop reads owner of undefined.

0.3 ships the same deepValue. It does not reach this call with an embedded path, because its query strategy registers only the relations named in the find options and joins eager relations into the main query instead. The call that makes the path reachable arrived with #11326.

Related

#10821 reports the same deepValue walking off the end of a path, reached through the select call sites rather than this one. It was closed by the stale-issue sweep in September 2025 without a fix, and the code it describes is unchanged.

Suggested fix

Return undefined as soon as a segment resolves to null or undefined, which is what all seven call sites already expect:

static deepValue(obj, path) {
    let value = obj
    for (const segment of path.split(".")) {
        if (value == null) {
            return undefined
        }
        value = value[segment]
    }
    return value
}

Environment

typeorm 1.1.0, better-sqlite3 12.11.1, Node 24.14.1. Reproduced on 1.1.0, not present on 0.3.31.

Activity

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