我有一个功能,基本上是verify if one can update the entry in the database > update the entry
使用ORM航行时(吃水线)。
当前端在api端点一次发送多个请求(或一次到达多个请求)时,会发生问题。那时,对这些条目的验证失败,更新条目意味着其他验证也会更改。
我尝试通过使用事务来解决此问题:据我所知,事务意味着数据存储更新阻止在另一个事务仍很忙时进行更新吗?
代码:
const new_entry = await sails.getDatastore().transaction(async (db) => {
console.log(`${entry_id}: transaction started`);
if (section_name) {
const event_id: number = typeof entry.event === 'number' ? entry.event : entry.event.id;
section = await Section.findOne({
where: {
name: section_name,
event: event_id,
}
}).usingConnection(db);
if (!section) {
throw new BadParamsError('section not found');
}
console.log(`${entry_id}: before full check`);
const existing = await Entry.find({
event: event_id,
section: section.id,
}).usingConnection(db);
console.log(`${entry_id}: before updating items: ${existing.length}`);
//if existing is larger than free spots do something....
section_id = section.id;
console.log(`${entry_id}: start update`);
const new_entry = await Entry.update({id: entry_id}).set({
section: section_id
}).usingConnection(db).fetch();
const existing_after = await Entry.find({
event: event_id,
section: section.id,
}).usingConnection(db);
console.log(`${entry_id}: after updating items: ${existing_after.length}`);
console.log(`${entry_id}: transaction ended`);
return new_entry;
}
console.log(`${entry_id}: transaction ended`);
return {};
});
但是我在日志中注意到的是:
48: transaction started
48: before full check
47: transaction started
48: before updating items: 0
48: start update
47: before full check
47: before updating items: 0
47: start update
48: after updating items: 1
48: transaction ended
47: after updating items: 1
47: transaction ended
所以这意味着它们都同时被更新,更糟糕的是,他们看不到彼此的更新。
在更新时如何在数据库上放置锁? -或者以其他方式防止出现这种情况?