测试事务隔离级别的代码块:
person.js
'use strict';
const { startTransaction, commit, rollback } = require('../utils/transaction');
module.exports = function (Person) {
Person.fun = async function () {
let tx;
try {
tx = await startTransaction(this, this.Transaction.READ_UNCOMMITTED);
const options = { transaction: tx };
let person = await Person.find({ where: { name: "ee" } }, options);
person[0].age = 10000;
await Person.upsert(person[0], options);
if(person.length > 0){
throw new Error("手动报错!");
}
await commit(tx);
}
catch (e) {
console.error(e);
if (tx)
rollback(tx);
}
};
Person.fun1 = async function () {
let tx;
try {
tx = await startTransaction(this, this.Transaction.READ_UNCOMMITTED);
const options = { transaction: tx };
let person = await Person.find({ where: { name: "ee" } }, options);
person[0].age = 10000;
await Person.upsert(person[0], options);
await commit(tx);
}
catch (e) {
console.error(e);
if (tx)
rollback(tx);
}
};
}
transaction.js
module.exports = {
startTransaction,
commit,
rollback
}
async function startTransaction(model, isolation) {
return new Promise((resolved, rejected) => {
isolation = isolation ? isolation : model.Transaction.REPEATABLE_READ;
model.beginTransaction({isolationLevel: isolation}, (err, tx) => {
if(err) return rejected(err);
resolved(tx);
});
});
}
async function commit(tx) {
return new Promise((resolved, rejected) => {
console.log('conmmit tx is active?:',tx.ensureActive(),tx.id);
tx.commit(err => {
// console.log('conmmit tx is active?:',tx.ensureActive(),tx.id);
if(err) return rejected(err);
resolved();
});
});
}
async function rollback(tx) {
return new Promise((resolved, rejected) => {
tx.rollback((err) => {
if(err) return rejected(err);
resolved();
});
});
}