drizzle-team / drizzle-team/drizzle-orm
[BUG]: Incorrect table name used in count query
- Dominant language
- TypeScript
- Stars
- 35.8k
- Forks
- 1.6k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 4
Description
### Report hasn't been filed before.
- [x] I have verified that the bug I'm about to report hasn't been filed before.
### What version of `drizzle-orm` are you using?
0.44.4
### What version of `drizzle-kit` are you using?
0.31.4
### Other packages
_No response_
### Describe the Bug
When using `db$.count` in a subquery of a relational query, the column used in the where clause has the wrong table name.
Schema:
```ts
export const lesson = pgTable(
"lesson",
{
id: text("id").primaryKey(),
title: text("title"),
subjectCode: text("subject_code")
.notNull()
.references(() => subject.code),
levelCode: text("level_code")
.notNull()
.references(() => level.code),
// Scheduling
date: date("date").notNull(),
startTime: time("start_time").notNull(),
endTime: time("end_time").notNull(),
locationCode: text("location_code")
.notNull()
.references(() => lessonLocation.code),
// Status
status: lessonStatusEnum("status").default(LessonStatus.DRAFT).notNull(),
// Communication & Notes
teacherNotes: text("teacher_notes"),
cancellationReason: text("cancellation_reason"),
cancelledBy: text("cancelled_by").references(() => user.id),
// Rescheduling (foreign keys will be added separately)
originalLessonId: text("original_lesson_id"),
rescheduledTo: text("rescheduled_to"),
// Timestamps
createdAt: timestamp("created_at")
.$defaultFn(() => new Date())
.notNull(),
updatedAt: timestamp("updated_at")
.$defaultFn(() => new Date())
.notNull(),
cancelledAt: timestamp("cancelled_at"),
completedAt: timestamp("completed_at"),
},
(table) => [
foreignKey({
columns: [table.originalLessonId],
foreignColumns: [table.id],
name: "lesson_original_lesson_fk",
}),
foreignKey({
columns: [table.rescheduledTo],
foreignColumns: [table.id],
name: "lesson_rescheduled_to_fk",
}),
]
);
export const lessonStudent = pgTable(
"lesson_student",
{
lessonId: text("lesson_id")
.notNull()
.references(() => lesson.id, { onDelete: "cascade" }),
studentId: text("student_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
enrolledAt: timestamp("enrolled_at")
.$defaultFn(() => new Date())
.notNull(),
},
(table) => [primaryKey({ columns: [table.lessonId, table.studentId] })]
);
```
Relations:
```ts
export const lessonRelations = relations(lesson, ({ one, many }) => ({
originalLesson: one(lesson, {
fields: [lesson.originalLessonId],
references: [lesson.id],
relationName: "lessonReschedule",
}),
rescheduledLesson: one(lesson, {
fields: [lesson.rescheduledTo],
references: [lesson.id],
relationName: "lessonReschedule",
}),
students: many(lessonStudent, {
relationName: "lessonStudents",
}),
}));
export const lessonStudentRelations = relations(lessonStudent, ({ one }) => ({
lesson: one(lesson, {
fields: [lessonStudent.lessonId],
references: [lesson.id],
}),
student: one(user, {
fields: [lessonStudent.studentId],
references: [user.id],
}),
}));
```
Query generating the wrong table name:
```ts
const lessonsQuery = db.query.lesson.findMany({
with: {
// ... other tables
},
extras: {
studentCount: db
.$count(lessonStudent, eq(lesson.id, lessonStudent.lessonId))
.as("studentCount"),
},
limit,
offset,
orderBy: [desc(lesson.date), desc(lesson.startTime)],
where: and(...conditions),
});
```
Generated query:
```sql
select
"lesson"."id",
-- ... other columns
(
select
count(*)
from
"lesson_student"
where
"lesson"."id" = "lesson"."lesson_id" -- BUG: Here the condition should be lesson.id = lesson_student.lesson_id
) as "studentCount",
"lesson_subject"."data" as "subject",
"lesson_level"."data" as "level",
"lesson_location"."data" as "location",
"lesson_cancelledByUser"."data" as "cancelledByUser"
from
"lesson" "lesson"
-- ... other joins
order by
"lesson"."date" desc,
"lesson"."start_time" desc
limit
$5
```
**Full files attached**
- Schema & Relations: [lessons.ts.txt](https://github.com/user-attachments/files/21633303/lessons.ts.txt)
- Query: [query.txt](https://github.com/user-attachments/files/21633314/query.txt)
- Generated SQL: [sql.txt](https://github.com/user-attachments/files/21633326/sql.txt)
Contributor guide
Assessment
This issue has not been assessed yet.