Skip to content

Question: transactions and concurrency #564

Closed
@olalonde

Description

@olalonde

From the Wiki:

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));
    });
  });
});

In this example, I noticed that the callbacks refer to the same global client object. What if while a query is being executed another query is executed from somewhere else in the code? How does node-postgres know which queries belong to the same transaction?

For example:

client.query('BEGIN', function(err, result) {
  client.query('INSERT INTO account(money) VALUES(100) WHERE id = $1', [1], function(err, result) {
      // Let's say an error happens here.... will the other transaction below be rolled back as well?
      if(err) return rollback(client);
      client.query('COMMIT', client.end.bind(client));
});

client.query('BEGIN', function(err, result) {
  client.query('INSERT INTO account(money) VALUES(200) WHERE id = $1', [1], function(err, result) {
      if(err) return rollback(client);
      client.query('COMMIT', client.end.bind(client));
});

It seems I could maybe solve this problem by using different clients for each transactions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions