본문 바로가기

Backend/Node.js

Node.js MySQL Transaction(트랜잭션)

노드에서 mysql 모듈을 사용할 때 트랜잭션 처리하는 방법에 대해서 알아볼게요.

아직 mysql을 연동하지 않았다면 이 글을 먼저 참고해주세요.

https://gofnrk.tistory.com/61

 

Node MySQL 연동 (Express)

Node.js에서 MySQL을 연동해볼게요. 연동하고 select, insert, update, delete 쿼리까지 실행시켜 볼거에요. 연동하고 사용하는 것 자체는 매우 간단해요. 우선, mysql2 모듈을 설치해줍니다. npm i mysql2 pool.j..

gofnrk.tistory.com

 

트랜잭션 예제는

게시글 댓글(board_comment)에 INSERT 하고, 게시글(board)에 댓글 수를 +1 UPDATE 해줄거에요.

board와 board_comment의 PK는 모두 auto_increment 설정하였습니다.

async/await 패턴

var express = require('express')
var router = express.Router()
const pool = require('../database/pool')

router.post('/:boardId/comment', async (req, res, next) => {
  const { boardId } = req.params
  const { content } = req.body

  const conn = await pool.getConnection()
  try {
    await conn.beginTransaction() // 트랜잭션 적용 시작

    const ins = await conn.query('insert into board_comment set ?', { board_id: boardId, content: content })
    const upd = await conn.query('update board set comment_cnt = comment_cnt + 1 where board_id = ?', [boardId])

    await conn.commit() // 커밋
    return res.json(ins)
  } catch (err) {
    console.log(err)
    await conn.rollback() // 롤백
    return res.status(500).json(err)
  } finally {
    conn.release() // conn 회수
})

 

insert, update, delete 쿼리를 호출하면 처리 결과를 json으로 받을 수 있어요.

변수명만 봐도 대강 어떤 데이터인지 알 수 있을거에요.

완성도 높은 로직을 작성할 때 사용하면 됩니다.

 

insert 결과 (위의 예제에서 const ins)

affectedRows : 생성된 rows 수

insertId : 생성된 row의 auto_increment로 만들어진 ID 값

 

[
	{
		"fieldCount": 0,
		"affectedRows": 1,
		"insertId": 14,
		"info": "",
		"serverStatus": 3,
		"warningStatus": 0
	},
	null
]

 

 

 

update 결과 (위의 예제에서 const upd)

affectedRows : where절로 검색된 rows 수

changedRows : 실제로 update된 rows 수

info : 처리 메시지

 

[
	{
		"fieldCount": 0,
		"affectedRows": 1,
		"insertId": 0,
		"info": "Rows matched: 1  Changed: 1  Warnings: 0",
		"serverStatus": 3,
		"warningStatus": 0,
		"changedRows": 1
	},
	null
]

 

 

 

delete 결과

affectedRows: 삭제 결과

 

[
    {
        "fieldCount": 0,
        "affectedRows": 1,
        "insertId": 0,
        "info": "",
        "serverStatus": 3,
        "warningStatus": 0
    },
    null
]

 

 

serverStatus 값은 그때 그때 찾아보면 됩니다.

2: Auto-Commit 상태

3: Transaction 상태