serverless-mysql icon indicating copy to clipboard operation
serverless-mysql copied to clipboard

Question about using transaction

Open sam26880 opened this issue 5 years ago • 1 comments

I want to dynamically run some queries as part of a transaction. I don't know ahead of time how many queries there will be. So I can't just do

results = await mysql.transaction().query(query1).query(query2);

there could be 3 or 5 queries. How do I make this logic work with this?

I tried this

results = await mysql.transaction().query(query1);
if(query2)
  results = results.query(query2);
if(query3)
 results = results.query(query3);

....and so on

and then finally

results.rollback(err => {
            console.log('Error running transaction:', err);
        })
        .commit() 

Does this seem right? I'm not seeing any errors when running this but it also doesn't seem to do anything. I don't see any rows of data being inserted or anything in my mysql table.

sam26880 avatar Sep 19 '19 17:09 sam26880

The docs have this use case for conditional queries ... more like this (from readme):

let results = await mysql.transaction()
  .query('DELETE FROM table WHERE id = ?', [someVar])
  .query((r) => {
    if (r.affectedRows > 0) {
      ['UPDATE anotherTable SET x = 1 WHERE id = ?', [someVar]]
    } else {
      return null
    }
  })
  .rollback(e => { /* do something with the error */ }) // optional
  .commit() // execute the queries

jdchmiel avatar Oct 01 '19 20:10 jdchmiel