0

I'm trying to create a temporary table, then execute a SELECT query on it using the node-pg library. Using promises and .then(), I wait for the table to be created (or it seems that should be the case), then do my selection query:

  const tempText = `
    CREATE TEMPORARY TABLE IF NOT EXISTS temp1 AS
    (
      SELECT colA, colB
      FROM foo
      GROUP BY colA, colB
    )
  `;

  const queryText = `
    SELECT colA, COUNT(colA) as total
    FROM temp1
    GROUP BY colA
    ORDER BY COUNT(colA) DESC
  `;
  // using pooling
  return db.query({ text: tempText, values })
    .then(() => {
      return db.query(queryText).then(({ rows }) => rows);
    })
    .catch((err) => { throw err; });

This code is all lives inside a GraphQL resolver. The trouble is, the first time I hit it via an API, I get "relation \"temp1\" does not exist", But all subsequent calls are successful and return data. Why would this be? I'm waiting for the first query to finish before doing the SELECT

1
  • Combine the two statements with the WITH operator as explained here. Commented Feb 11, 2020 at 19:16

1 Answer 1

3

Temporary tables are specific to a session, and separate db.query() calls aren’t guaranteed to run in the same session, since db is a pool that acquires a client separately for each query() call. Grab a client explicitly:

return db.connect().then(async client => {
  try {
    await client.query({ text: tempText, values });
    const result = await client.query(queryText);
    return result.rows;
  } finally {
    client.release();
  }
});

Note also that .catch((err) => { throw err; }) doesn’t do anything.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.