drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[BUG]: Fix issue with wrong aliasing with nested query in rqb

Open livingforjesus opened this issue 1 month ago • 1 comments

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.7

What version of drizzle-kit are you using?

0.31.6

Other packages

No response

Describe the Bug

I have a (relatively giant) query where I get errors like

 ERROR:  invalid reference to FROM-clause entry for table "Order" at character 985
Perhaps you meant to reference the table alias "orders".

A subset of the query is something like

await db.query.orders.findMany({
  where: // where clause
  with: // .. other tables...
  extras: {
     status: sql.raw(`CASE WHEN ${eq(orders.key, "Value")} THEN ${1} ..... END`)
  }
}

My current workaround is to do something like

// We do this because of a drizzle bug which doesn't use the right alias
const asRawOrdersColumn = (
	column: (typeof orders)[keyof typeof orders.$inferSelect],
) => sql.raw(`"orders"."${column.name}"`);

livingforjesus avatar Nov 07 '25 13:11 livingforjesus

Can confirm. same issue occurs with following code

// For table firstTable
where: exists(
    db.select({id: secondTable.id}).from(secondTable).where(eq(secondTable.refId, firstTable.id))
)

produces exists (select "id" from "secondTable" where "secondTable"."ref_id" = "table1"."id")

error: invalid reference to FROM-clause entry for table "table1"
length: 195,
severity: "ERROR",
detail: undefined,
hint: "Perhaps you meant to reference the table alias \"firstTable\".",

m41denx avatar Nov 10 '25 21:11 m41denx