Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized query with string literal in node-postgres

I'm trying to write a node-postgres query that takes an integer to use in an interval as a parameter:

  const query = {
    text:
      `SELECT
        foo 
        FROM bar 
        WHERE 
          DATE(created_at) >= DATE(NOW()) - INTERVAL '$1 DAYS';`,
    values: [daysAgo]
  }

When I run this, it gives this error message indicating it's not seeing the $1 because it's enclosed in single quotes:

bind message supplies 1 parameters, but prepared statement "" requires 0

Is there a supported way to do this? If not, what is the best work around?

like image 664
alexroussos Avatar asked Oct 28 '25 01:10

alexroussos


1 Answers

I found this reference which shows you can use the convention of '1 DAY' * X.

I was able to get this working thus:

   (async () => {
       const { rows } = await pgpool.query(`
          SELECT id, name FROM users 
           WHERE DATE(created) <= DATE(NOW()) - INTERVAL '1 DAY' * $1;`,
           [req.params.daysAgo]);
like image 103
rotarydial Avatar answered Oct 29 '25 18:10

rotarydial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!