Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with Dynamic Columns in Queries #1011

Open
lsferreira934 opened this issue Jan 17, 2025 · 0 comments
Open

Issue with Dynamic Columns in Queries #1011

lsferreira934 opened this issue Jan 17, 2025 · 0 comments

Comments

@lsferreira934
Copy link

lsferreira934 commented Jan 17, 2025

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant