question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Resolve array of queries in one Transaction

See original GitHub issue

Using a global connection like here #164 for use Transaction. I think this works but how i can do to resolve a array of queries using transaction or multiples transactions, the code i put works only for one querie.

routes/set1Transaction.js

var sql     = require('mssql');

module.exports = function(globalConnection) {
   return function(req, res, next) {
      var transaction = new sql.Transaction(globalConnection);
      transaction.begin(function(err) {
          // ... error checks

             var request = new sql.Request(transaction);
             request.query('insert into mytable (mycolumn) values (12345)', function(err, recordset) {
                 // ... error checks

             transaction.commit(function(err, recordset) {
                  // ... error checks

              console.log("Transaction commited.");
                  });
            });
       });
       req.results=recordset;
       next();

    }

};

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

16reactions
melounekcommented, Jun 20, 2018

I found this during my solution research and I think for v4.x this is nicer with ES6 and async/await

    const transaction = await new sql.Transaction()
    transaction.begin(async err => {
      try{
        const request = new sql.Request(transaction)
        const result1 = await request.query`query1`
        const result = await request.query`query2`
        transaction.commit(tErr => tErr && next('transaction commit error'))
      }catch(err){
        transaction.rollback(tErr => tErr && next('transaction rollback error'))
        next('unknown error inside transaction = rollback')
      }
    })
5reactions
estvmachinecommented, Sep 8, 2015

Hi, only im passing for says thanks and told how i resolved this, i used a constructor function named ‘setUpMultipleQueries’, is a forEach using the ‘listQuery’. Well i leave the code. Thanks!

var sql = require('mssql');
var async = require('async');

var transaction = new sql.Transaction(globalConnection);
transaction.begin(function(err) {
    if (err) {
        return console.error('Error in transaction begin', err);
    }

      var request = new sql.Request(transaction);
      var listQuery= setUpMultipleQueries(req.consultas, request);  /*HERE IS THE MAGIC*/

      async.series( listQuery,

    function(err, results) {
        // results is now equal to: {one: [{a: 1}], two: [{b: 2}]}
        if (err) {
            console.error('Error in queries, rolling back', err);
            return transaction.rollback();
        }
        transaction.commit(function(err) {
            if (err) {
                return console.error('Error in commit', err);
            }
            console.log("Transaction commited.");
            console.log(results);
        });
    });
});

function setUpMultipleQueries(listQuery, request){
  var requestObject= {};
  listQuery.forEach(function(query, index){
    console.log(index);
      requestObject['q'+index]= function(callback){
            request.query(query, callback);
      };
  });
  return requestObject;
};


Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Implement Multiple Queries Transactions with Node.JS ...
The easiest way to solve this is by having a function that runs a transaction on an undefined number queries and returning all...
Read more >
mysql - how to run transaction of a dynamic array of queries
I used node-mysql-transaction var transaction = require('node-mysql-transaction'); var trCon = transaction({connection: [mysql.
Read more >
Transactions and promises in Node.js | by Pavel Romanov
We have a database which need to be consistently updated with some batch of data and Node.JS application which executes queries in database....
Read more >
Multi-statement transactions | BigQuery - Google Cloud
The following query returns the active transactions for a particular job, specified by the ID of the job that is running the multi-statement...
Read more >
node_modules/pg-promise - GitLab - SMHI
Transactions, functions, flexible query formatting; ... When a value/property inside array/object is an array, it is treated as a PostgreSQL Array Type, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found