egg-sequelize-autotrx
This plugin helps to do transaction auto pass down and solve the nested transaction issue.
Problems
After CLS enabled, nested transaction will have unexpected result:
async nestedTrx () {
await this.ctx.model.transaction(async () => {
await this.ctx.model.M1.create()
await this.ctx.model.transaction(async () => {
await this.ctx.model.M2.create()
await this.ctx.model.M3.create()
})
await this.ctx.model.M4.create()
})
}
If error throw out from M4 creation, transaction will rollback creation for M1 and M4. M2 and M3 will be committed. To make all the operations commit and rollback together through out all the transactions, you need help from this plugin.
Internally, this plugin solves the problem by passing parent transaction down to the child transaction:
async nestedTrx () {
await this.ctx.model.transaction(async parentTrx => {
await this.ctx.model.M1.create()
await this.ctx.model.transaction({ transaction: parentTrx }, async () => {
await this.ctx.model.M2.create()
await this.ctx.model.M3.create()
})
await this.ctx.model.M4.create()
})
}
Install
$ npm i egg-sequelize-autotrx --save
Usage
You need to use egg-sequelize plugin first, and have it CLS enabled with cls-hooked:
single datasource
const mySequelize = require('sequelize')
const clsNamespace = require('cls-hooked').createNamespace('your-namespace')
mySequelize.useCLS(clsNamespace)
module.exports = appInfo => {
const config = exports = {}
config.sequelize = {
Sequelize: mySequelize,
dialect: 'mysql',
}
}
multiple datasource
const mySequelize1 = require('sequelize')
const mySequelize2 = require('sequelize')
const clsNamespace1 = require('cls-hooked').createNamespace('your-namespace1')
const clsNamespace2 = require('cls-hooked').createNamespace('your-namespace2')
mySequelize1.useCLS(clsNamespace1)
mySequelize2.useCLS(clsNamespace2)
module.exports = appInfo => {
const config = exports = {}
config.sequelize = {
datasources: [{
Sequelize: mySequelize1,
delegate: 'model1',
dialect: 'mysql'
}, {
Sequelize: mySequelize2,
delegate: 'model2',
dialect: 'mysql'
}]
}
enable sequelize-autotrx plugin:
exports.sequelizeAutotrx = {
enable: true,
package: 'egg-sequelize-autotrx',
}
Configuration
exports.sequelizeAutotrx = {
}
see config/config.default.js for more detail.
Example
Let's see a real case:
async nestedTransactionTest () {
await this.ctx.model.transaction(async () => {
await this.ctx.model.Project.create()
await this.innerTrx()
await this.ctx.model.User.create()
})
}
async innerTrxCanBeExecAlone () {
await this.nestedTrx()
}
async innerTrx () {
await this.ctx.model.transaction(async () => {
})
}
Questions & Suggestions
Please open an issue here.
License
MIT