postgres icon indicating copy to clipboard operation
postgres copied to clipboard

AS in Dynamic Fields Selection Not Working

Open chauhankiran opened this issue 1 year ago • 2 comments

I've a columns variable in which I'm conditionally adding column name based on whether field is enable or not. There is one field createdBy which I want to select as creator.email AS creatorEmail where creator is an alias of the users table. Following is the sample code.

let columns = [];

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

// ... other fields condition

if (view.field === "createdBy") {
  columns.push("creator.email AS creatorEmail");
}

Then following the query I'm trying to run.

sql`
  select
    ${sql(columns)}
  from
    companies
  join
    users as creator
  on
    companies."createdBy" = creator.id`

But, it throw error as

PostgresError: column creator.email AS creatorEmail does not exist

Postgres condering complete string as column name and not As as keyword of Postgres.

Note: I saw one issue where someone suggested to use fragment. But, can I've an example of it? I tried with many different syntax and it doesn't work.

chauhankiran avatar Jun 15 '24 16:06 chauhankiran