Manual transaction management is a treacherous path, try to steer away from that! ;)
Here's how to do it properly, with the help of pg-promise:
function(req, res) {
db.tx(t => { // automatic BEGIN
return t.one('INSERT_1 VALUES(...) RETURNING id', paramValues)
.then(data => {
var q = t.none('INSERT_2 VALUES(...)', data.id);
if (req.body.value != null) {
return q.then(()=> t.none('INSERT_3 VALUES(...)', data.id));
}
return q;
});
})
.then(data => {
res.send("Everything's fine!"); // automatic COMMIT was executed
})
.catch(error => {
res.send("Something is wrong!"); // automatic ROLLBACK was executed
});
}
Or, if you prefer ES7 syntax:
function (req, res) {
db.tx(async t => { // automatic BEGIN
let data = await t.one('INSERT_1 VALUES(...) RETURNING id', paramValues);
let q = await t.none('INSERT_2 VALUES(...)', data.id);
if (req.body.value != null) {
return await t.none('INSERT_3 VALUES(...)', data.id);
}
return q;
})
.then(data => {
res.send("Everything's fine!"); // automatic COMMIT was executed
})
.catch(error => {
res.send("Something is wrong!"); // automatic ROLLBACK was executed
});
}
UPDATE
Replaced ES6 generators with ES7 async
/await
in the example, because pg-promise stopped supporting ES6 generators from version 9.0.0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…