mysqljs / mysql

A pure node.js JavaScript Client implementing the MySQL protocol.
MIT License
18.27k stars 2.52k forks source link

[simple] README clarification on pooled transaction #2520

Closed henrymcl closed 3 years ago

henrymcl commented 3 years ago

Please consider adding the comments below for README's Transactions part.

connection.beginTransaction(function(err) {
  if (err) { throw err; }
  connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) {
    if (error) {
      return connection.rollback(function() {
        // remember to connection.release() if it's pool connection
        throw error;
      });
    }

    var log = 'Post ' + results.insertId + ' added';

    connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) {
      if (error) {
        return connection.rollback(function() {
          // remember to connection.release() if it's pool connection
          throw error;
        });
      }
      connection.commit(function(err) {
        if (err) {
          return connection.rollback(function() {
            // remember to connection.release() if it's pool connection
            throw err;
          });
        }
        // remember to connection.release() if it's pool connection
        console.log('success!');
      });
    });
  });
});
dougwilson commented 3 years ago

Hello, and thank you for the suggestion. There is no requirement to release the connection back to the pool if there is an error in those locations. You can make more queries if you want; when to release is very dependent on your application. Adding those comments would be misleading.