postgres icon indicating copy to clipboard operation
postgres copied to clipboard

Issue with Dynamic Columns in Queries

Open lsferreira934 opened this issue 9 months ago • 0 comments

I'm experiencing an issue with dynamic columns in queries when using postgres.js. I have a structure where functions dynamically build the query, as shown below:

function sendConsult(query) {
  return dbpg`
    SELECT COUNT(_id)
    FROM positions
    WHERE status = 'active'
      AND company_id = ${companyId}
      ${addFilters('position', companyId, query)}
  `;
}

const addFilters = (source, companyId, query) => {
  if (source === 'position') {
    const date = { 
        from: moment(query.from).format('YYYY-MM-DD'),
        to: moment(query.to).format('YYYY-MM-DD 23:59:59')
    }
    const columns = { one: 'positions."archivedAt"', two: 'positions."releasedAt"' };
    return dbpg`${filterDateBy(columns, '$case', date)}`;
  }
};

const filterDateBy = (field, operator, date) => {
  const { from, to } = date;

  const clause = {
    '$case': from && to ? dbpg`AND CASE
        WHEN positions.status = 'closed'
        THEN DATE_TRUNC('day', ${field.one}) > ${from}
          AND DATE_TRUNC('day', ${field.two}) <= ${to}
        ELSE DATE_TRUNC('day', ${field.two}) <= ${to}
      END` : dbpg``,
  };

  return clause[operator];
};

When executing the query, I get an error stating that the dynamically passed columns (field.one or field.two) do not exist. However, if I print the generated query (without using the dbpg instance) and execute it directly in DBeaver, it works as expected.

Question: Is there a native way in postgres.js to handle dynamic columns so the query works correctly? If not, are there any recommendations to address this limitation?

Thank you in advance for the support!

lsferreira934 avatar Jan 17 '25 13:01 lsferreira934