Serverless MySQL v1.1.0 adds additional transaction support to allow users to get interim query results. This is useful for getting the insertId
from previous queries when performing transactions.
Transactions are extremely simple with Serverless MySQL. You just need to start a transaction, chain your queries, and then use the commit()
method to execute them.
1 2 3 4 5 |
let results = await mysql.transaction() .query('INSERT INTO table (x) VALUES(?)', [1]) .query('UPDATE table SET x = 1') .rollback(e => { /* do something with the error */ }) // optional .commit() // execute the queries |
Now, with the new interim query results support, you can retrieve the results of the previous query by wrapping your query in a function and returning an array containing your new query’s attributes:
1 2 3 4 5 |
let results = await mysql.transaction() .query('INSERT INTO table (x) VALUES(?)', [1]) .query((r) => ['UPDATE table SET x = 1 WHERE id = ?', r.insertId]) .rollback(e => { /* do something with the error */ }) // optional .commit() // execute the queries |
If you need to get the value of multiple queries, you can use the second argument instead:
1 2 3 4 5 6 7 8 9 |
let results = await mysql.transaction() .query('INSERT INTO table (x) VALUES(?)', [1]) .query('INSERT INTO otherTable (y) VALUES(?)', [2]) .query((r,results) => [ 'UPDATE table SET x = ? WHERE id = ?', [ results[1].insertId, results[0].insertId ] ]) .rollback(e => { /* do something with the error */ }) // optional .commit() // execute the queries |
Easy peasy 🍋! Check out the Serverless MySQL NPM module to see how simple it is to manage MySQL at Serverless Scale.
NPM: https://www.npmjs.com/package/serverless-mysql
GitHub: https://github.com/jeremydaly/serverless-mysql
Tags: aurora, aurora serverless, mysql, rds, serverless
Did you like this post? 👍 Do you want more? 🙌 Follow me on Twitter or check out some of the projects I’m working on.
Learn more about Serverless MySQL or check out the other projects I'm working on.
Hi Jeremy, would be great if I could use this with Knex.js. Any ideas on how to integrate?
Hi Samin,
Knex.js uses its own interface into the
mysql
package, so I don’t think it is possible to useserverless-mysql
with it. You might be able to monkey patch Knex, but you’d have to experiment.– Jeremy