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

Python 의 Transaction — Implicit 모델

~14 min · python, transactions, isolation_level

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

Python sqlite3 의 가장 surprising 한 부분

Python sqlite3 모듈이 SQLite 위에 자기 implicit transaction 동작 가짐. 기본값이 자주 사람들 놀래.

  • 기본값: 첫 DML statement (INSERT/UPDATE/DELETE) 전 자동 transaction open.
  • Non-DML statement (CREATE TABLE 등) 전 자동 commit — 유명한 'PRAGMA inside transaction' 버그 원천.
  • 모듈의 isolation_level 속성이 이걸 제어. conn.isolation_level = None 이 implicit transaction 끔 — BEGIN/COMMIT 로 explicit 관리.

대부분 결국 쓰는 Pythonic 패턴:

  • with conn: — context manager: implicit BEGIN, 성공 시 COMMIT, exception 시 ROLLBACK.
  • 또는 isolation_level = None 설정 + 명시적 conn.execute('BEGIN IMMEDIATE').
Warning: Python 3.12 가 legacy isolation_level 보다 명확한 새 autocommit 속성 추가. 새 코드는 명시적 transaction 의 autocommit=False, 또는 autocommit=True 의 autocommit-style 선호. 옛 코드는 isolation_level; 양 API 공존.

Code

with conn — 일상 패턴·python
import sqlite3

conn = sqlite3.connect('demo.db')

with conn:
    conn.execute('INSERT INTO users(email) VALUES (?)', ('a@x.com',))
    conn.execute('INSERT INTO users(email) VALUES (?)', ('b@x.com',))
    # 여기서 exception = ROLLBACK; 깨끗 종료 = COMMIT.
명시적 transaction 제어·python
import sqlite3

conn = sqlite3.connect('demo.db', isolation_level=None)  # autocommit-ish

conn.execute('BEGIN IMMEDIATE')
try:
    conn.execute('INSERT INTO orders(...) VALUES (...)')
    conn.execute('UPDATE inventory SET qty = qty - 1 WHERE id = ?', (sku,))
    conn.execute('COMMIT')
except Exception:
    conn.execute('ROLLBACK')
    raise

External links

Exercise

Python transaction 동작 3 가지 시연: (1) with conn: implicit transaction, (2) isolation_level = None explicit transaction, (3) open transaction 안에서 PRAGMA 돌리면 implicit transaction commit 되는 버그. 각각 동작 드러내는 짧은 테스트 + 본인 코드에 어느 패턴 쓸지 결정.

Progress

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

댓글 0

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

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