Skip to content

Commit

Permalink
fix: handle concurrent transaction (#85)
Browse files Browse the repository at this point in the history
  • Loading branch information
killagu committed Feb 11, 2021
1 parent fb81c4e commit d983478
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,16 @@ proto.beginTransaction = function* () {
proto.beginTransactionScope = function* (scope, ctx) {
ctx = ctx || {};
if (!ctx._transactionConnection) {
ctx._transactionConnection = yield this.beginTransaction();
// Create only one conn if concurrent call `beginTransactionScope`
ctx._transactionConnection = this.beginTransaction();
}
const tran = yield ctx._transactionConnection;

if (!ctx._transactionScopeCount) {
ctx._transactionScopeCount = 1;
} else {
ctx._transactionScopeCount++;
}
const tran = ctx._transactionConnection;
try {
const result = yield scope(tran);
ctx._transactionScopeCount--;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"eslint-config-egg": "^3.2.0",
"istanbul": "*",
"mocha": "8",
"mz-modules": "^2.1.0",
"thunk-mocha": "*"
},
"homepage": "https://github.com/ali-sdk/ali-rds",
Expand Down
24 changes: 24 additions & 0 deletions test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const assert = require('assert');
const mysql = require('mysql');
const rds = require('../');
const config = require('./config');
const sleep = require('mz-modules/sleep');

describe('client.test.js', function() {
const prefix = 'prefix-' + process.version + '-';
Expand Down Expand Up @@ -414,6 +415,29 @@ describe('client.test.js', function() {
assert.equal(ctx._transactionScopeCount, 3);
});
});

it('should safe with yield Array', function* () {
const ctx = {};
yield [
this.db.beginTransactionScope(function* (conn) {
yield conn.query(
'INSERT INTO `ali-sdk-test-user` (name, email, mobile) values(?, ?, "12345678901")',
[ prefix + 'should-safe-with-yield-array-1', prefix + 'm@should-safe-with-yield-array-1.com' ]
);
yield sleep(100);
}, ctx),
this.db.beginTransactionScope(function* (conn) {
yield conn.query(
'INSERT INTO `ali-sdk-test-user` (name, email, mobile) values(?, ?, "12345678901")',
[ prefix + 'should-safe-with-yield-array-2', prefix + 'm@should-safe-with-yield-array-1.com' ]
);
yield sleep(200);
}, ctx),
];
const rows = yield this.db.query(
'SELECT * FROM `ali-sdk-test-user` where name like "%should-safe-with-yield-array%"');
assert(rows.length === 2);
});
});

describe('beginDoomedTransactionScope(scope)', function() {
Expand Down

0 comments on commit d983478

Please sign in to comment.