@@ -5,7 +5,7 @@ ALTER TABLE events
55 ADD COLUMN IF NOT EXISTS store_id BIGINT ;
66
77/* ============================================================
8- * 2. Legacy Store 생성 (없으면 생성, 있으면 재사용 )
8+ * 2~4 . Legacy Store 생성 + backfill (events/users )
99 * ============================================================ */
1010DO
1111$$
3636 RETURNING id INTO v_store_id;
3737 END IF;
3838
39- /* ========================================================
40- * 3. 기존 이벤트 → Legacy Store로 backfill
41- * ======================================================== */
39+ /* 3. 기존 이벤트 → Legacy Store로 backfill */
4240 UPDATE events
4341 SET store_id = v_store_id
4442 WHERE store_id IS NULL ;
4543
46- /* ========================================================
47- * 4. 기존 ADMIN 사용자 → Legacy Store로 backfill
48- * - store_id가 NULL인 경우만
49- * - deleted_at IS NULL (소프트 삭제 제외)
50- * ======================================================== */
44+ /* 4. 기존 ADMIN 사용자 → Legacy Store로 backfill */
5145 UPDATE users
5246 SET store_id = v_store_id
5347 WHERE role = ' ADMIN'
5852
5953/* ============================================================
6054 * 5. events.store_id NOT NULL 강제
55+ * - 이미 3번에서 NULL backfill 했으므로 안전
6156 * ============================================================ */
6257ALTER TABLE events
6358 ALTER COLUMN store_id SET NOT NULL ;
6459
6560/* ============================================================
66- * 6. FK 제약 추가
61+ * 6. FK 제약 추가 (이미 존재하면 스킵)
6762 * ============================================================ */
68- ALTER TABLE events
69- ADD CONSTRAINT fk_events_store
70- FOREIGN KEY (store_id) REFERENCES stores (id);
63+ DO
64+ $$
65+ BEGIN
66+ -- events FK
67+ IF NOT EXISTS (SELECT 1
68+ FROM pg_constraint
69+ WHERE conname = ' fk_events_store' ) THEN
70+ ALTER TABLE events
71+ ADD CONSTRAINT fk_events_store
72+ FOREIGN KEY (store_id) REFERENCES stores (id);
73+ END IF;
7174
72- ALTER TABLE users
73- ADD CONSTRAINT fk_user_store
74- FOREIGN KEY (store_id) REFERENCES stores (id);
75+ -- users FK
76+ IF NOT EXISTS (SELECT 1
77+ FROM pg_constraint
78+ WHERE conname = ' fk_user_store' ) THEN
79+ ALTER TABLE users
80+ ADD CONSTRAINT fk_user_store
81+ FOREIGN KEY (store_id) REFERENCES stores (id);
82+ END IF;
83+ END
84+ $$;
7585
7686/* ============================================================
7787 * 7. 인덱스 (조회/조인 성능)
@@ -80,4 +90,4 @@ CREATE INDEX IF NOT EXISTS idx_events_store_id
8090 ON events (store_id);
8191
8292CREATE INDEX IF NOT EXISTS idx_users_store_id
83- ON users (store_id);
93+ ON users (store_id);
0 commit comments