Postgres promise a few requests - nodejs

After reading https://stackoverflow.com/a/312616/2126/ about the only nodejs thread and that it takes the first parameter of the async function, processes it, and then uses the callback to answer when everything is ready. I was confused that if I had several requests that needed to be excused right away, and tell nodeJS about blocking other requests by adding them to the queue.

For this, I realized that I need to wrap my requests in another callback. And promises do it pretty well.

    const psqlClient = psqlPool.connect(); 
    return psqlClient.query(`SELECT username FROM usernames WHERE username=$1`, ['me'])
    .then((data) => {
        if(!data.rows[0].username) {
           psqlClient.query(`INSERT INTO usernames (username) VALUES ('me')`);
        }
       else { ... } 
 });

This code is used during registration to check if the username was not accepted before insertion. Therefore, it is very important that nodejs put other requests in the queue and at the same time monitor selectand insert. Since this code can allow people with the same username to simultaneously send a username that has already been accepted, so two usernames will be inserted.

Questions

  • Does the code above execute all requests at the same time?

  • If 1true, if I had to change code like this

    const psqlClient = psqlPool.connect(); 
    return psqlClient.query(`SELECT username FROM usernames WHERE username=$1`, ['me'], function(err, reply) { 
    if(!reply.rows[0].username) {
    psqlClient.query(`INSERT INTO usernames (username) VALUES ('me')`);
    }
    });
    

    will this affect behavior?

  • 1 , ? ( , select insert/update ) , , XML Sitemap 50000 URL-, db, .

+4
2

, , - SELECT->INSERT, .

:

;)


SELECT ⇒ INSERT pg-promise.


, , , . .

+2

node -postgres: https://github.com/brianc/node-postgres/issues/83#issuecomment-212657287. , , ....

BEGIN COMIT

var Client = require('pg').Client;

var client = new Client(/*your connection info goes here*/);
client.connect();

var rollback = function(client) {
  //terminating a client connection will
  //automatically rollback any uncommitted transactions
  //so while it not technically mandatory to call
  //ROLLBACK it is cleaner and more correct
  client.query('ROLLBACK', function() {
    client.end();
  });
};

client.query('BEGIN', function(err, result) {
  if(err) return rollback(client);
  client.query('INSERT INTO account(money) VALUES(100) WHERE id = $1', [1], function(err, result) {
    if(err) return rollback(client);
    client.query('INSERT INTO account(money) VALUES(-100) WHERE id = $1', [2], function(err, result) {
      if(err) return rollback(client);
      //disconnect after successful commit
      client.query('COMMIT', client.end.bind(client));
    });
  });
});

: https://github.com/brianc/node-postgres/wiki/Transactions

. : , Postgres ( )

0

Source: https://habr.com/ru/post/1657878/


All Articles