postgres
postgres copied to clipboard
Enable dynamic column aliases
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
I fixed the typo that caused the checks to fail.
@porsager will this PR be accepted?
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?
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.
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"