CodeFoodPixels / node-promise-mysql

A wrapper for mysqljs/mysql that wraps function calls with Bluebird promises.
MIT License
338 stars 63 forks source link

How to do Transactions? #34

Closed yi-ge closed 7 years ago

yi-ge commented 7 years ago

thank you.

CodeFoodPixels commented 7 years ago

Something like this:

var mysql = require('promise-mysql');
var connection;

mysql.createConnection({
    host: 'localhost',
    user: 'sauron',
    password: 'theonetruering',
    database: 'mordor'
}).then(function(conn){
    connection = conn;

    return connection.beginTransaction();
}).then(function(){
    return connection.query('INSERT INTO log SET data=?', 'badger');
}).then(function() {
    return connection.commit();
}).catch(function(){
    return connection.rollback();
});

This should work, but I've not run the code.

zawadzkip commented 7 years ago

Is there any way to do this using async/await syntax? Just curious to see if it is possible

CodeFoodPixels commented 7 years ago

I've not used async/await, but as fast as I know it should just work as async/await just needs calls to return promises. I think it's something like this:

var mysql = require('promise-mysql');
var connection = await mysql.createConnection({
    host: 'localhost',
    user: 'sauron',
    password: 'theonetruering',
    database: 'mordor'
})

try {
    await connection.beginTransaction();
    await connection.query('INSERT INTO log SET data=?', 'badger');
    await connection.commit();
} catch () {
    await connection.rollback();
}

This code was written on my phone and is untested, but it should give you an idea.

zawadzkip commented 7 years ago

@lukeb-uk Thank you!