Skip to content

Postgres: unconditional nested join parentheses in 1.1.0 constrain the planner and regress query plans #12792

Closed

Description

@daniel5150

Issue description

1.1.0 wraps a join and its children in parentheses whenever the join has children. For LEFT nested under LEFT this is semantically a no-op, but it constrains the PostgreSQL planner's join-order search and can cause large plan regressions.

Same underlying change as #12764, different symptom.

Expected Behavior

Nest only where flat emission would change results — an INNER child under an OUTER parent. Where parent and child are both LEFT, 1.0.0's flat form is equivalent and leaves the planner free.

Actual Behavior

Nesting is unconditional whenever childJoins is non-empty — query-builder/SelectQueryBuilder.js:

buildJoinClause(direction, tableName, alias, condition, childJoins = "") {
    const prefix  = childJoins ? "(" : "";
    const postfix = childJoins ? ")" : "";
    ...
}

1.0.0 emitted joinAttributes as a flat list; 1.1.0 builds a tree and emits it via createJoinTreeRecursively().

Steps to reproduce

@Entity() class Country { @PrimaryColumn() id: number }

@Entity() class Profile {
  @PrimaryColumn() id: number
  @Column() countryId: number
  @ManyToOne(() => Country) @JoinColumn({ name: 'countryId' }) country: Country
}

@Entity() class User {
  @PrimaryColumn() id: number
  @Column() profileId: number
  @ManyToOne(() => Profile) @JoinColumn({ name: 'profileId' }) profile: Profile
}
repo.createQueryBuilder('u')
  .leftJoinAndSelect('u.profile', 'p')
  .leftJoinAndSelect('p.country', 'c')

1.0.0:

FROM "user" "u"
LEFT JOIN "profile" "p" ON "p"."id" = "u"."profileId"
LEFT JOIN "country" "c" ON "c"."id" = "p"."countryId"

1.1.0:

FROM "user" "u"
LEFT JOIN ("profile" "p"
           LEFT JOIN "country" "c" ON "c"."id" = "p"."countryId")
       ON "p"."id" = "u"."profileId"

Identical results — only planner freedom differs.

Impact

PostgreSQL 18.1, a query joining 7 tables off a ~570k-row root with one LEFT nested under another, ordered by a left-joined column with LIMIT/OFFSET. On upgrading 1.0.0 → 1.1.0 every pre-upgrade queryid in pg_stat_statements stopped accumulating at deploy time and traffic moved to new queryids containing JOIN (, averaging ~19s.

Suggested fix

Gate the parentheses on semantic necessity rather than the presence of children: nest when a child would otherwise alter outer-join semantics, emit flat otherwise.

My Environment

Dependency Version
operating system Linux (container)
node.js 24.19.0
typeorm 1.1.0
PostgreSQL 18.1

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