brianc / node-postgres

PostgreSQL client for node.js.
https://node-postgres.com
MIT License
12.04k stars 1.21k forks source link

I can't use parameters with more than a digit #3226

Closed emafriedrich closed 1 month ago

emafriedrich commented 1 month ago

If i try to use a parameter that is in the params array with a index > 9, the parameter is incorrectly parsed.

Test made


    export const connection = new Pool({
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      port: +process.env.DB_PORT! || 5432,
    });

    const Query = require('pg').Query;
    const submit = Query.prototype.submit;
    Query.prototype.submit = function() {
      const text = this.text;
      const values = this.values;
      if (values) {
        const query = values.reduce((q: any, v: any, i: any) => q.replaceAll(`$${i + 1}`, v), text);
        console.log(query);
      } else {
        console.log(text);
      }
      submit.apply(this, arguments);
    };

    await connection.query('select $12 from quotes', [
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
      'foo',
    ])

console.log shows

select foo2 from quotes

Version 8.11.3

boromisp commented 1 month ago

You can use any number of parameters with the library, as this library does not parse the query string, it just passes it to the server to handle.

You seem to be doing the parsing yourself, by monkey patching Query.submit.

What are you trying to achieve? Are you trying to avoid the extended protocol for some reason?

emafriedrich commented 1 month ago

sorry @boromisp , my bad. It was a mistake in the snippet that you refer. I found it in the web to log the queries. Not sure if the library has support for logging queries, for that I looked into the web for some logging approach.

import { Pool } from "pg";

const connection = new Pool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  port: +process.env.DB_PORT! || 5432,
});

const test = async () => {
  const result = await connection.query(
    `SELECT
      $1 a,
      $2 b,
      $3 c,
      $4 d,
      $5 e,
      $6 f,
      $7 g,
      $8 h,
      $9 i,
      $10 j,
      $11 k,
      $12 l
   `,
    [
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
      "foo",
    ]
  );

  console.log(result.rows[0]);
};

(async () => await test())();

And all was resolved fine.