drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
24.68k stars 651 forks source link

[BUG]: findMany (and likely others) building an invalid query when other tables are referenced in the where clause #3573

Open nobledossy opened 1 week ago

nobledossy commented 1 week ago

Report hasn't been filed before.

What version of drizzle-orm are you using?

0.36.2

What version of drizzle-kit are you using?

0.28.1

Other packages

No response

Describe the Bug

This is possibly related to #3268, but may be a separate issue.

I have a query I'm trying to run on a Postgres database. It's fairly straightforward, but I'm getting an error thrown due to the assembled query being invalid. As an abridged and sterilized version of what I've got:

export const Table1 = pgTable(
  'table_1',
  {
    id: uuid('id').defaultRandom().primaryKey(),
    accountType: pgAccountType('accountType'), //This is a pgEnum, works fine
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true })
      .defaultNow()
      .$onUpdate(() => new Date()),
  }
);

export const table1Relations = relations(Table1, ({ one, many }) => ({
  table2entries: many(Table2),
}));

export const Table2 = pgTable('table_2', {
  id: uuid('id').defaultRandom().primaryKey(),
  table1id: uuid('table_1_id')
    .references(() => Table1.id, { onDelete: 'cascade' })
    .notNull(),
  field1: varchar('field_1', { length: 255 }).notNull(),
  createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
  updatedAt: timestamp('updated_at', { withTimezone: true })
    .defaultNow()
    .$onUpdate(() => new Date()),
}
);

export const table2relations = relations(Table2, ({ one, many }) => ({
  table1entry: one(Table1, {
    fields: [Table2.table1id],
    references: [Table1.id],
  }),
}));

Pretty straightforward one-to-many relationship. I'm trying to do the following query (type = enum, field1s = string array):

const result = await this.db.query.Table1.findMany({
      where: and(eq(Table1.accountType, type), inArray(Table2.field1, field1s)),
      with: {
        table2entries: true,
      },
    }).execute();

This throws an error with the following exception:

error: column Table1.field1 does not exist

It's as if it's taking the table queried and automatically applying it to any column in the where clause even though it's explicitly defined otherwise. I need this in the top where clause as I need it to be a full filter and not effectively a left join with a condition. Is this not a supported configuration or am I doing something wrong here? I would think this should work, but I don't think I've explicitly attempted this combination until recently. Aliasing the tables does not help.