postgres icon indicating copy to clipboard operation
postgres copied to clipboard

Enable dynamic column aliases

Open DictyosteliumDiscoideum opened this issue 11 months ago • 2 comments

Fixes #894.

Updates the parser to enable column aliases (i.e., "AS" statements) when columns are given in a dynamic array).

The syntax uses a nested array with two elements:

let columns = [];

if (view.field === "id") {
  columns.push("companies.id");
}

// ... other fields condition

if (view.field === "createdBy") {
  columns.push(["creator.email", "creatorEmail"]);
}
// columns = ["companies.id", ["creator.email", "creatorEmail"]]
sql`
  select
    ${sql(columns)}
  from
    companies
  join
    users as creator
  on
    companies."createdBy" = creator.id`

Which will produce:

SELECT "companies.id","creator.email" AS "creatorEmail"
FROM companies JOIN users as creator ON 
companies."createdBy" = creator.id

DictyosteliumDiscoideum avatar Dec 16 '24 06:12 DictyosteliumDiscoideum

I fixed the typo that caused the checks to fail.

DictyosteliumDiscoideum avatar Dec 17 '24 01:12 DictyosteliumDiscoideum

@porsager will this PR be accepted?

flauc avatar May 31 '25 18:05 flauc

Looks like the checks on the test/ are still failing. Echoing flauc's question above. If it's not being accepted, do we have a working example (workaround) to deal with aliases in dynamic column select statements?

nomoney4me avatar Aug 20 '25 00:08 nomoney4me

I don't have time to fix this at the moment but I will see if I can get to it.

In the meantime, you can use query fragments: https://github.com/porsager/postgres?tab=readme-ov-file#building-queries. It's clunky but it should work.

DictyosteliumDiscoideum avatar Sep 06 '25 23:09 DictyosteliumDiscoideum

I don't have time to fix this at the moment but I will see if I can get to it.

In the meantime, you can use query fragments: porsager/postgres#building-queries. It's clunky but it should work.

I'm having a hard time figuring out how to get it to work. I've also read https://github.com/porsager/postgres/issues/894#issuecomment-2183862823 but it looks like something has changed since then?

Here is what I have:

let cols = '';
  cols += 'id as "members.id"';
  const queryResult =
    await sql`select ${sql.unsafe(cols)} from membership.members WHERE ${sql(lookupKey)} IN ${sql(lookupValues)}`;
  return queryResult;

Edit: I've also read the fragment portion and came up with

const fragAs = sql`as members.id`;
const queryResult =
  await sql`select id ${fragAs} from membership.members WHERE ${sql(lookupKey)} IN ${sql(lookupValues)}`;
return queryResult;

This is also not working as intended and produces the error: syntax error at or near "$1"

nomoney4me avatar Oct 30 '25 14:10 nomoney4me