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

FK (켜!)

~12 min · foreign-keys, constraints, writes

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

기본값 OFF — 켜야 함

SQLite 가 FK 지원하는데 backward 호환 위해 기본값 OFF. connection 마다 켜야 함:

PRAGMA foreign_keys = ON;

가장 흔한 SQLite 사고. Schema 가 FK 선언 받아주고 다이어그램은 맞아 보이는데, FK 위반 insert 가 silently 성공 — 엔진이 체크 안 하니까. 피파를 비롯한 모든 SQLite 프레임워크가 새 connection 마다 이 PRAGMA 돌려.

Warning: PRAGMA foreign_keys 는 connection 단위, DB 단위 아님. 모든 connection 의 첫 statement 로. Connection pool 은 connect_args / on-connect callback 에서 처리해야 함.

활성화 후 FK 가:

  • Parent 테이블에 매치 안 되는 FK insert 거부.
  • Child orphan 만드는 parent 삭제 거부 (ON DELETE CASCADE 등 명시 안 한 한).
  • 옵션으로 update/delete cascade — w08.

Code

켜고 동작 확인·sql
PRAGMA foreign_keys = ON;

CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT) STRICT;
CREATE TABLE posts (
  id INTEGER PRIMARY KEY,
  author_id INTEGER NOT NULL REFERENCES authors(id),
  title TEXT NOT NULL
) STRICT;

INSERT INTO posts(author_id, title) VALUES (999, 'Orphan');
-- Error: FOREIGN KEY constraint failed
Python — 모든 connection 에 PRAGMA·python
import sqlite3

def connect(path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(path)
    conn.execute('PRAGMA foreign_keys = ON')
    conn.execute('PRAGMA journal_mode = WAL')
    return conn

External links

Exercise

Fresh DB 에서 authors + posts 만들고 FK 선언. PRAGMA 켜기 orphan insert — 성공 관찰! 그 다음 PRAGMA 켜고 재시도. 한 코드 path 에서 PRAGMA 잊으면 production 에서 만들 버그 클래스 문서화.

Progress

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

댓글 0

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

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