Drizzle TeamDT
Drizzle Team3y ago
5 replies
cal

`sql.join` with `ODER BY` leads to syntax error while the sql query seems correct.

I am conditionally sorting the results from a database query
const sortSqlChunks: SQL[] = [];
if (sorting.length > 1) {
  const customSort = sorting.shift();
  if (customSort) {
    const [property, order] = Object.entries(customSort)[0];
    sortSqlChunks.push(
      sql`${ad[property as unknown as keyof AdSelect]} ${order} nulls last`,
    );
  }
}
sortSqlChunks.push(sql`${ad.publisherCreatedDateTime} desc nulls last`);

const ads = await this.dataAccessService
      .getDb("AD")
      .select()
      .from(ad)
      .where(inArray(ad.publicId, elasticSearchAds.publicIds))
      .orderBy(sql.join(sortSqlChunks, ", "));


The query builder returns the following query

{
  sql: 'select ... from "ads"."Ad" where "Ad"."publicId" in (...) order by "Ad"."price" $26 nulls last$27"Ad"."publisherCreatedDateTime" desc nulls last',
  params: [
    ...
    'desc',
    ', '
  ]
}


Which seems to be correct. When executing the code I get the following PostgresError:
syntax error at or near \"$26\"


Something seems to be off with 'desc' but I don't have a clue what is causing this.

Any help is appreciated
Was this page helpful?