본문 바로가기
C.W.K.
Stream
Lesson 08 of 10 · published

Connection Pragma + 설정

~12 min · python, pragma, configuration

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

외울 만한 'production-ready opener'

SQLite를 쓰는 production Python 앱은 대부분 connection을 여는 작은 헬퍼를 하나씩 갖게 돼. 매번 똑같은 PRAGMA 묶음을 거는 함수 말이야. 목록과 이유는 이래.

  • journal_mode = WAL — reader와 writer가 같이 굴러가게 해. track 4에서 다뤘어.
  • synchronous = NORMAL — WAL과 함께라면 안전하면서 FULL보다 빨라.
  • foreign_keys = ON — FK를 실제로 검사하게 만들어. 이것도 track 4에서.
  • busy_timeout = 5000 — 잠깐 걸린 락에 바로 터지지 않고 조금 기다리게 해.
  • temp_store = MEMORY — 임시 B-tree를 디스크가 아니라 RAM에 둬.
  • cache_size = -64000 — read가 많은 워크로드를 위해 page cache를 64 MB로 잡아.
  • mmap_size = 134217728 — 큰 파일을 빠르게 읽으려고 128 MB를 mmap I/O로 잡아.
Self-reference: 피파의 backend/store/conversations.py가 정확히 이 묶음으로 모든 connection을 열어. cache와 mmap 크기만 프로젝트에 맞춰 조정했고. 100k row짜리 JSONL과 SQLite 기록 위에서도 WebUI가 즉각 반응하는 것처럼 느껴지는 건 이 일곱 설정 덕분이야.

Code

모든 프로젝트에 복붙할 opener·python
import sqlite3, atexit

def open_db(path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(path, timeout=30.0, isolation_level=None)
    conn.row_factory = sqlite3.Row
    for pragma in (
        'PRAGMA journal_mode = WAL',
        'PRAGMA synchronous = NORMAL',
        'PRAGMA foreign_keys = ON',
        'PRAGMA busy_timeout = 5000',
        'PRAGMA temp_store = MEMORY',
        'PRAGMA cache_size = -64000',     # 64 MB
        'PRAGMA mmap_size = 134217728',   # 128 MB
    ):
        conn.execute(pragma)
    atexit.register(lambda: (conn.execute('PRAGMA optimize'), conn.close()))
    return conn

External links

Exercise

sqlite3를 기본 설정 그대로 쓰는 네 Python 스크립트를 하나 골라. connection 여는 부분을 위 production-ready 버전으로 바꿔봐. 갖고 있던 벤치마크를 다시 돌리고, 어느 PRAGMA가 네 워크로드에서 가장 크게 효과를 냈는지 적어둬.

Progress

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

댓글 0

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

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