UnManaged Transaction
- Commit, Rollback을 수동으로 사용하여 Transaction을 관리하는 것을 의미
const { sequelize } = require("../models/index.js");
// Sequelize의 트랜잭션을 변수에 할당하여 트랜잭션을 시작합니다.
const t = await sequelize.transaction();
try {
const user = await User.create({
firstName: '용우',
lastName: '이',
}, { transaction: t }); // 해당 쿼리에 트랜잭션을 적용합니다.
// 트랜잭션을 사용한 모든 로직을 Commit, DB에 반영합니다.
await t.commit();
} catch(transactionError) {
// 에러가 발생하였다면, 트랜잭션을 사용한 모든 쿼리를 Rollback, DB에 반영하지 않습니다.
await t.rollback();
}
ISOLATION LEVEL 설정
- Transaction을 생성할 때 Property를 정의할 수 있다.
const { Transaction } = require("sequelize");
const t = await sequelize.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED, // 트랜잭션 격리 수준을 설정합니다.
});
Managed Transaction
- Sequelize가 자체적으로 Transaction의 성공과 실패를 관리
const { sequelize } = require("../models/index.js");
// 콜백으로 함수를 할당하여 비즈니스로직을 처리합니다.
const result = await sequelize.transaction( async(t) => {
const user = await User.create({
firstName: '용우',
lastName: '이',
}, { transaction: t }); // 해당 쿼리에 트랜잭션을 적용합니다.
return user;
});
ISOLATION LEVEL 설정
const { Transaction } = require('sequelize');
await sequelize.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE
}, async (t) => {
// Your code
});