S
S
SEOD2020-02-10 07:11:35
PostgreSQL
SEOD, 2020-02-10 07:11:35

How to work correctly in NodeJS with PostgreSQL?

I do not understand how the client pool functions. I need multiple applications to use the same Postgre database at the same time.
Reading the article: https://node-postgres.com/features/pooling I come across an expression:

You must __always__ return the client to the pool if you successfully check it out, regardless of whether or not there was an error with the queries you ran on the client. If you don't check in the client your application will leak them and eventually your pool will be empty forever and all future requests to check out a client from the pool will wait forever.

I didn't understand anything at all. I make queries like this:
const {Pool} = require("pg");
const pool = new Pool({
  host: "127.0.0.1",
  port: 5432,
  database: "mydb",
  user: "user1",
  password: "pwd",
});
(async () => {
  let query = "SELECT datnameasfd FROM pg_database;";
  let res = await pool.query(query);
})();

Is this correct or not? But there is not even a client here. I don't understand if it is necessary to do this at all and in what case it is necessary. How will the implementation change if my web server processes hundreds of requests and I need a persistent-connection? In which case should pool.end() be added at the end?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladlen Hellsite, 2020-02-10
@SEOVirus

Connections are stored in the pool, say 10 pieces. Every time we call pool.query() we are requesting a connection. If there is a connection, a request is made, and then its status is updated in the pool to free. If all connections are already busy, wait until the first available one is released. The documentation says that you must return connections to the pool (otherwise, when the connection limit in the pool approaches, requests will be waited indefinitely). And pool.end() should be called when you no longer need the current query pool, for example, you temporarily created it for another database? The pool itself will create connections as needed, of course it will not go beyond the limits, otherwise we would spend all the resources on creating connections.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question