트랜잭션의 문제를 해결한 후 실행된 쿼리를 보는데 난 분명 update를 실행했는데 select문이 실행되는 걸 보았다. 이것이 바로 매니저님이 말씀하신 ORM의 문제...! 그럼 rawquery로 변경하면 뭔가 호출되는 쿼리문이 줄어들까? 궁금해졌다.
로우쿼리 변경 전
if (show.quantity > 0) { console.log('query 시작 전'); await prisma.shows.update({ where: { showId: +showId }, data: { quantity: { decrement: 1 } }, }); console.log('query 시작 후'); } else { console.log(`${userId} : 예매수량부족`); throw new Error('예매 수량이 부족합니다.'); }
로우쿼리로 변경후
if (show.quantity > 0) { //console.log('query 시작 전'); //await prisma.shows.update({ // where: { showId: +showId }, // data: { quantity: { decrement: 1 } }, //}); //console.log('query 시작 후'); console.log('rawQuery 시작 전'); await tx.$executeRaw`UPDATE Shows SET quantity = quantity-1 WHERE showId=${showId};`; console.log('rawQuery 시작 후'); } else { console.log(`${userId} : 예매수량부족`); throw new Error('예매 수량이 부족합니다.'); }
3줄짜리 쿼리가 단 한줄로..! 이런식으면 성능개선도 할수있지않을까? 라는 생각이 들었고, 그렇게 코드들을 수정하기 시작했다. 이제 하나하나씩 코드를 확인해가면서 변경을 했다. find와 같은 코드들은 select문 하나만 불러오기때문에 굳이 바꿀필요가 없어보여 그냥 prisma문법으로 두었다.
로우쿼리로 개선안해도 되는 코드
console.log('시작 전'); const show = await tx.shows.findFirst({ where: { showId: +showId }, }); console.log('시작 후');
로우쿼리로 개선해야하는 코드들
if (user.credit >= show.price) { console.log('1 rawQuery 시작 전'); await tx.users.update({ where: { userId: +userId }, data: { credit: user.credit - show.price }, }); console.log('1 rawQuery 시작 후'); console.log('2 rawQuery 시작 전'); await tx.reservation.create({ data: { UserId: user.userId, ShowId: show.showId }, }); console.log('2 rawQuery 시작 후'); } else { console.log(`${userId} : credit부족`); throw new Error('보유한 credit이 부족합니다.'); }
개선 후
if (user.credit >= show.price) { console.log('1 Query 시작 전'); await tx.$executeRaw`UPDATE users SET credit = credit - ${show.price} WHERE userId=${userId};`; console.log('1 Query 시작 후'); console.log('2 Query 시작 전'); await tx.$executeRaw`INSERT INTO reservation(UserId, ShowId) VALUES (${user.userId}, ${show.showId});`; console.log('2 Query 시작 후'); } else { console.log(`${userId} : credit부족`); throw new Error('보유한 credit이 부족합니다.'); }
와우. 드라마틱하게 줄었다. 5줄이 2줄이 되는 마법..!
좋아 그럼 로우쿼리를 만들기 전과 후의 성능 차이를 알아보자.
우선 duration: 60, arrivalRate: 10, count:10으로 진행했다.
로우쿼리 전
로우쿼리 후
결과 : 조금이지만 성능의 개선이 보였다.
