node.jspg

have to I add on every query a release?


I have this query:

const data = async () => {
  try {
   await client.query('SELECT * FROM data');
 } catch(e) {
   return e;
 }
};

but I see that people use it like this:

const data = async () => {
  try {
   await client.query('SELECT * FROM data');
 } catch(e) {
   return e;
 } finally {
  client.release();
}
};

so whats the difference and should I use method 2 ?


Solution

  • I assume you are using node-postgres.

    You should not call client.release() for every query you run with client.query(). You have to call client.release() once (and only once) when you are done with the the database connection client.

    Where and when you should call client.release() depends on the structure of your application.

    If you just need to run one query, it is better to just use pool.query() instead of checkout a client.