node.js, pg module and done() method

2.8k views Asked by At

Using the pg module and clients pool I need to call done() method in order to return the client into clients pool.

Once I connect to the server, I add SQL query client’s query queue and I start handling the result asynchronously row by row in row event:

// Execute SQL query
var query = client.query("SELECT * FROM categories");
// Handle every row asynchronously
query.on('row', handleRow );

When I should call done() method? Should I call it once I receive the end event and all rows are processed or I can call it immediately after I add SQL query to the client’s query queue?

2

There are 2 answers

0
juanpaco On BEST ANSWER

Going from an example on this project's page (https://github.com/brianc/node-pg-query-stream), I'd recommend calling it when you get the end event.

This makes sense, because you're not done with it until you're received the last row. If someone else got that same connection and tried using it, that would likely create odd errors.

0
gabssnake On

The former makes sense: you would want to call it once you know you have processed all rows for your query.

// your DB connection info
var conString = "pg://admin:admin@localhost:5432/Example";

var pg = require("pg");
var client = new pg.Client(conString);
client.connect();

// Your own query
var query = client.query("SELECT * FROM mytable");

query.on("row", function (row, result) {
  // do your stuff with each row
  result.addRow(row);
});

query.on("end", function (result) {
  // here you have the complete result
  console.log(JSON.stringify(result.rows, null, 2));
  // end when done ;)
  client.end();
});