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

Transaction — BEGIN, COMMIT, ROLLBACK

~14 min · transactions, acid, writes

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

원자적 작업 묶음

Transaction = statement 그룹을 한 원자 단위로: 다 적용 또는 하나도 적용 안 함. SQLite 는 기본값으로 완전 ACID — single statement 도 implicit transaction 안에서 돌아.

3 가지 명시적 모양:

  • BEGIN; ... COMMIT; — 명시 transaction, 성공 시 commit.
  • BEGIN; ... ROLLBACK; — BEGIN 이후 모든 변경 abort.
  • SAVEPOINT — outer transaction 안의 nested 체크포인트. 성공 시 RELEASE, 실패 시 ROLLBACK TO.

SQLite transaction 모드:

  • DEFERRED (기본) — 필요할 때만 락 획득.
  • IMMEDIATE — BEGIN 에서 write 락 획득, 다른 writer 즉시 block.
  • EXCLUSIVE — exclusive 락, 다른 reader/writer 모두 block.
Tip: 다른 writer 와 경쟁 가능한 'all-or-nothing' workflow 면 BEGIN IMMEDIATE 써. 기본 DEFERRED 는 다른 writer 가 먼저 도착하면 COMMIT 시점에 SQLITE_BUSY 로 실패할 수 있음 — IMMEDIATE 는 BEGIN 에서 빨리 실패.

Code

SQL 의 명시적 transaction·sql
BEGIN IMMEDIATE;

INSERT INTO conversations(title) VALUES ('New chat');
INSERT INTO messages(conversation_id, role, content)
VALUES (last_insert_rowid(), 'user', 'Hello');

-- COMMIT 전 뭔가 실패하면 전체 batch 롤백 가능:
-- ROLLBACK;

COMMIT;
Python — context manager 가 commit/rollback 처리·python
import sqlite3

conn = sqlite3.connect('demo.db')
conn.execute('PRAGMA foreign_keys = ON')

try:
    with conn:                                  # implicit BEGIN/COMMIT
        conv_id = conn.execute(
            'INSERT INTO conversations(title) VALUES (?)',
            ('New chat',)
        ).lastrowid
        conn.execute(
            'INSERT INTO messages(conversation_id, role, content) VALUES (?,?,?)',
            (conv_id, 'user', 'Hello'),
        )
        # 여기서 exception 나면 자동 ROLLBACK.
except sqlite3.IntegrityError:
    print('rolled back')

External links

Exercise

Conversation + message list 를 atomic 으로 insert 하는 Python 함수. 루프 중간에 일부러 raise 해서 롤백 동작 확인. 그 다음 동시 writer 두 개로 BEGIN DEFERRED vs BEGIN IMMEDIATE 차이 contention 환경에서 관찰.

Progress

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

댓글 0

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

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