mysql - 在 Sequelize(MySQL) 中,如何使用多个事务?
问题描述
我尝试使用 Sequelize 将数据放入 M:N 关系的联结表中,但失败了。
该错误在下面详细说明。
起初我以为这个问题是在 Sequelize 的关系模型中。
不过google了一下,以为是mysql引擎的lock_wait_timeout选项有问题,于是想了各种办法解决。
我被告知将事务拆分为多个,但我不知道如何在我的代码中应用它。
你能告诉我怎么做吗?
// 错误日志
0|app | { Error: Lock wait timeout exceeded; try restarting transaction
0|app | at Packet.asError (/home/ec2-user/mepus_test/node_modules/my sql2/lib/packets/packet.js:712:17)
0|app | at Query.execute (/home/ec2-user/mepus_test/node_modules/mys ql2/lib/commands/command.js:28:26)
0|app | at Connection.handlePacket (/home/ec2-user/mepus_test/node_m odules/mysql2/lib/connection.js:425:32)
0|app | at PacketParser.Connection.packetParser.p [as onPacket] (/ho me/ec2-user/mepus_test/node_modules/mysql2/lib/connection.js:75:12)
0|app | at PacketParser.executeStart (/home/ec2-user/mepus_test/node _modules/mysql2/lib/packet_parser.js:75:16)
0|app | at Socket.Connection.stream.on.data (/home/ec2-user/mepus_te st/node_modules/mysql2/lib/connection.js:82:25)
0|app | at Socket.emit (events.js:198:13)
0|app | at addChunk (_stream_readable.js:288:12)
0|app | at readableAddChunk (_stream_readable.js:269:11)
0|app | at Socket.Readable.push (_stream_readable.js:224:10)
0|app | code: 'ER_LOCK_WAIT_TIMEOUT',
0|app | errno: 1205,
0|app | sqlState: 'HY000',
0|app | sqlMessage: 'Lock wait timeout exceeded; try restarting transa ction',
0|app | sql:
0|app | 'INSERT INTO `User_Gathering` (`status`,`like`,`book_mark`,`u ser_idx`,`gathering_idx`) VALUES (1,0,0,1,7);',
0|app | parameters: undefined },
// 路由代码
let putGathering = async function (req, res) {
await sequelize.transaction(async transaction => {
try {
const user = await User.findOne({
where: {
email: req.body.email,
},
}, { transaction: transaction });
const category = await Category.findOne({
where: {
category_name: req.body.categoryName,
},
}, { transaction: transaction });
const [location, created] = await Location.findOrCreate({
where: {
location_name: req.body.meetLoc,
},
transaction,
});
const gathering = await Gathering.create({
title: req.body.meetTitle,
date: req.body.meetDate,
time: req.body.meetTime,
content: req.body.content,
maxnum: req.body.maxNum,
minnum: req.body.minNum,
maxage: req.body.maxAge,
minage: req.body.minAge,
}, { transaction: transaction });
await category.addGathering(
gathering,
{ transaction },
);
await location.addGathering(
gathering,
{ transaction },
);
console.log(10); // This log is worked.
await gathering.addUser(
user,
{
through: {
status: 1,
like: 0,
book_mark: 0,
}
},
{ transaction },
);
console.log(11); // This log is not worked. I think there is a problem int upper code.
res
.status(201)
.json({
responseMsg: 'succeed',
})
} catch (err) {
console.error(err);
}
});
};