Skip to content

TypeError when combining leftJoinAndSelect with addOrderBy on date fields #11808

Closed

Description

@Simon3640

Issue description

TypeORM throws a TypeError: Cannot read properties of undefined (reading 'databaseName') when combining leftJoinAndSelect with addOrderBy on date fields (e.g., created_at, updated_at) from a joined entity.

Expected Behavior

The query should execute successfully and return the PermissionRole entities with their related Permission entities, ordered by the created_at field of the Permission entity.

Actual Behavior

TypeORM throws a TypeError: Cannot read properties of undefined (reading 'databaseName') when trying to process the ORDER BY clause combined with the SELECT expression from the joined entity.

Steps to reproduce

  1. Create two entities with a ManyToOne relationship
  2. Use leftJoinAndSelect to join the related entity
  3. Apply addOrderBy on a date field (e.g., created_at, updated_at) from the joined entity
  4. Call getMany() on the query builder

Minimal Reproduction Code

import { DataSource } from "typeorm";
import { 
  Entity, 
  Column, 
  ManyToOne, 
  JoinColumn, 
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn
} from "typeorm";

// Base entity with date fields
abstract class BaseEntity {
  @PrimaryGeneratedColumn("uuid")
  id!: string;

  @CreateDateColumn({ name: "created_at" })
  createdAt!: Date;

  @UpdateDateColumn({ name: "updated_at" })
  updatedAt!: Date;

  @DeleteDateColumn({ name: "deleted_at", nullable: true })
  deletedAt!: Date | null;
}

// Permission entity
@Entity({ name: "permissions" })
class Permission extends BaseEntity {
  @Column({ type: "varchar", length: 100 })
  name!: string;

  @Column({ type: "varchar", length: 255, nullable: true })
  description?: string;

  @Column({ type: "enum", enum: ["CREATE", "READ", "UPDATE", "DELETE"], name: "action" })
  action!: string;

  @Column({ type: "enum", enum: ["USER", "ROLE", "PERMISSION"], name: "resource" })
  resource!: string;
}

// PermissionRole entity (junction table)
@Entity({ name: "permission_role" })
class PermissionRole extends BaseEntity {
  @Column({ name: "role_id", type: "uuid" })
  roleId!: string;

  @Column({ name: "permission_id", type: "uuid" })
  permissionId!: string;

  @ManyToOne(() => Permission, { onDelete: "CASCADE" })
  @JoinColumn({ name: "permission_id" })
  permission!: Permission;
}

// Reproducing the error
async function reproduceError(dataSource: DataSource, roleId: string) {
  const permissionRoleRepository = dataSource.getRepository(PermissionRole);

  const query = permissionRoleRepository
    .createQueryBuilder("pr")
    .leftJoinAndSelect("pr.permission", "p")
    .where("pr.roleId = :roleId", { roleId })
    .addOrderBy("p.created_at", "ASC"); // This causes the error

  // Error occurs here when calling getMany()
  const result = await query.getMany();
  return result;
}

// Alternative: Ordering by other date fields also fails
async function reproduceErrorWithUpdatedAt(dataSource: DataSource, roleId: string) {
  const permissionRoleRepository = dataSource.getRepository(PermissionRole);

  const query = permissionRoleRepository
    .createQueryBuilder("pr")
    .leftJoinAndSelect("pr.permission", "p")
    .where("pr.roleId = :roleId", { roleId })
    .addOrderBy("p.updated_at", "DESC"); // This also causes the error

  const result = await query.getMany(); // Error occurs here
  return result;
}

My Environment

  • TypeORM version: 0.3.27
  • Database: PostgreSQL
  • Node.js version: 24.5
  • TypeScript version: 5.9.2
  • OS: Linux

Additional Context

  • This issue is particularly problematic when working with junction tables and ordering by fields from related entities
  • The error is consistent and reproducible with date fields (created_at, updated_at, deleted_at) from joined entities
  • The issue occurs specifically with @CreateDateColumn, @UpdateDateColumn, and @DeleteDateColumn decorators when they have custom name options
  • The workaround using getRawMany() works but requires manual mapping, which is less convenient than using getMany()
  • The error does NOT occur when:
    • Ordering by fields from the main entity (e.g., pr.created_at)
    • Ordering by non-date fields from joined entities (e.g., p.name)
    • Using getRawMany() instead of getMany()
  • Similar issues have been reported in the TypeORM community when combining joins with ordering on date columns

Relevant Database Driver(s)

  • aurora-mysql
  • aurora-postgres
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • spanner
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

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

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

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

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions