C.W.K.
Stream
Lesson 02 of 10 · published

BEGIN, COMMIT, ROLLBACK

~10 min · transactions, control

Level 0스키마 새싹
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

세 제어 statement

BEGIN (또는 START TRANSACTION) 가 트랜잭션 열기. COMMIT 이 finalise — 모든 변경이 다른 세션에 visible 하고 디스크에 durable. ROLLBACK 이 다 버림. 99% 시간 쓸 트랜잭션 제어 statement 셋.

앱측 패턴

모든 DB 드라이버가 이거 감쌈. Python psycopg 에서: conn.commit() / conn.rollback(). SQLAlchemy 에서: 세션 commit() 또는 context manager. Node pg: client.query('COMMIT') / client.query('ROLLBACK'). Semantics 동일; syntax 가 감쌈.

실패 케이스 항상 처리

전형 버그: BEGIN, statement 실행, COMMIT — 그러나 어느 statement 가 예외 던지면 트랜잭션이 열린 채 idle. 그 connection 의 다음 statement 가 "current transaction is aborted" 에러. 예외에 항상 롤백.

Code

Python psycopg — 명시 트랜잭션·python
import psycopg
with psycopg.connect("postgresql://...") as conn:
    with conn.transaction():
        # 이 블록 안 모든 게 한 트랜잭션.
        conn.execute("UPDATE accounts SET balance = balance - 500 WHERE id = 1")
        conn.execute("UPDATE accounts SET balance = balance + 500 WHERE id = 2")
    # Context exit 에 commit; 예외에 rollback.
Node pg — 수동 try/catch/finally·javascript
const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query('UPDATE accounts SET balance = balance - 500 WHERE id = 1');
  await client.query('UPDATE accounts SET balance = balance + 500 WHERE id = 2');
  await client.query('COMMIT');
} catch (err) {
  await client.query('ROLLBACK');
  throw err;
} finally {
  client.release();
}

External links

Exercise

작은 스크립트 (어떤 언어든) 작성: 트랜잭션 열고, update 두 개, ROLLBACK. 아무것도 변경 안 된 거 확인. COMMIT 으로 같은 스크립트 실행 후 두 update visible 한지 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.