Open fknop opened 7 months ago
Here is a temporary workaround if someone needs it.
export const mysqlDialect = new MySqlDialect();
/**
* @example
* db.query.locations.findFirst({
* extras: (fields) => {
* return {
* ...countRelation("equipmentCount", fields.id, equipmentLocations.locationId),
* };
* },
* };
*/
export const countRelation = <const T extends string>(name: T, fieldId: MySqlColumn, refId: MySqlColumn): { [Key in T]: SQL.Aliased<number> } => {
const sqlChunks = sql`(SELECT COUNT(*) FROM ${refId.table} WHERE ${refId} = ${fieldId})`;
const rawSQL = sql.raw(mysqlDialect.sqlToQuery(sqlChunks).sql);
return {
[name]: rawSQL.mapWith(Number).as(name),
} as { [Key in T]: SQL.Aliased<number> };
};
Might be doing something extra, but it works and still gives type safety.
What version of
drizzle-orm
are you using?0.29.3
What version of
drizzle-kit
are you using?0.20.12
Describe the Bug
I'm using sql
` to add a subquery for a SELECT COUNT(*) in the
extras` field of the query API. Here is the snippet:Example of the generated query:
The generated query generates
project_branches.branch_id
for the${translationsTable.branchId}
interpolation instead oftranslations.branch_id
. I've tried using the same interpolation outside ofextras
using this snippet:And it properly generates the following SQL:
I Managed to reproduce in this code sandbox here with a simple user - issue - comment schema https://codesandbox.io/p/devbox/kind-galois-tk5yg6?file=%2Fapp%2Fpage.tsx
It seems to only happen at least one level of
with
deepExpected behavior
The sql`` properly interpolates the table name
Environment & setup
No response