porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.09k stars 259 forks source link

Error swap between completing and failing query in build step (with max connections = 1) #729

Open alessandroblaco opened 8 months ago

alessandroblaco commented 8 months ago

Hi, with the following conditions:

  1. the max number of connections is set to 1
  2. the connection is already open
  3. two queries are run at the same time

If the second query fails the build step, the build error is thrown on the first query, and the second query never resolves nor throws.

The bug occurs also for any n >= 2, as in the squared parenthesis in the comments.

const postgres = require("postgres");

(async () => {
  const sql = postgres({
    // important: max should be 1 [ n - 1 ]
    max: 1
  });
  try {
    // connection must exists. If this query is not run the bug does not occurs
    await sql`SELECT 2`;

    // 2 [n] queries. The first [first to (n-1)th] one is ok, but the second [nth] should fail in the build step
    await Promise.all([
      // this is a valid query and should resolve. It throws the error in the second query instead
      sql`SELECT 1`.catch((e) => {
        console.log(
          "Catched error from other query",
          e,
          e.query /* SELECT 1*/
        );
      }),
      // this query should fail *in the build step*. It never resolves/throws
      sql`SELECT ${undefined}`.catch((e) => {
        console.log("Never catched: this line won't be logged", e, e.query);
      }),
    ]);
    console.log("This line will never be logged");
  } catch (error) {
    console.log("This line will never be logged. Error in one promise: ", error);
    throw error;
  }
  await sql.end();
})().catch((e) => {
  console.error("Error", e);
});

I'm sorry, I tried but cannot suggest the fix.