-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_db_tables.py
More file actions
128 lines (109 loc) · 4.92 KB
/
Copy pathcreate_db_tables.py
File metadata and controls
128 lines (109 loc) · 4.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import sqlite3
import os
from pathlib import Path
def create_tables_v3():
# -------------------------------------------------------
# 1. 스마트 경로 설정 (자동 감지)
# -------------------------------------------------------
# 현재 스크립트 파일의 절대 경로
current_script_path = Path(__file__).resolve()
current_folder_name = current_script_path.parent.name
# 스크립트가 'scripts' 폴더 안에 있으면 2단계 위로, 아니면 1단계 위로
if current_folder_name == "scripts":
project_root = current_script_path.parent.parent
else:
project_root = current_script_path.parent
# DB 파일 목표 경로: Backend/databases/main.db
db_folder = project_root / "databases"
db_path = db_folder / "main.db"
print("=" * 60)
print(f"📍 스크립트 위치: {current_script_path}")
print(f"📂 프로젝트 루트: {project_root}")
print(f"💾 생성될 DB 경로: {db_path}")
print("=" * 60)
# 경로가 맞는지 사용자 확인 (Backend가 포함되어 있는지)
if "Backend" not in str(project_root) and "backend" not in str(project_root):
print("⚠️ 경고: 'Backend' 폴더가 경로에 보이지 않습니다.")
print(" 스크립트가 Backend 폴더 내부에 있는지 확인해주세요.")
# -------------------------------------------------------
# 2. 폴더 생성 및 기존 파일 처리
# -------------------------------------------------------
if not db_folder.exists():
print(f" 👉 '{db_folder.name}' 폴더가 없어서 새로 만듭니다.")
db_folder.mkdir(parents=True, exist_ok=True)
# -------------------------------------------------------
# 3. 테이블 생성
# -------------------------------------------------------
try:
conn = sqlite3.connect(str(db_path))
cursor = conn.cursor()
print(" ✅ 데이터베이스 연결 성공!")
# (1) 사용자 테이블
cursor.execute("""
CREATE TABLE IF NOT EXISTS tbl_users (
user_id TEXT PRIMARY KEY,
company_name TEXT NOT NULL,
access_code TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
""")
# [추가] 기본 테스트 사용자 계정 삽입 (INSERT OR IGNORE 사용)
# OR IGNORE를 사용하면 스크립트를 여러 번 실행해도 중복 데이터가 쌓이지 않습니다.
cursor.execute("""
INSERT OR IGNORE INTO tbl_users (user_id, company_name, access_code)
VALUES ('admin', '한성대학교', 'abcde1212');
""")
# (2) 검색 기록 테이블
cursor.execute("""
CREATE TABLE IF NOT EXISTS search_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL, -- ★ 대화 세션을 식별하는 키
query TEXT NOT NULL,
result_count INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
""")
# (3) 라이브러리 테이블
cursor.execute("""
CREATE TABLE panel_library (
library_id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL, -- 원본 세션 ID
name TEXT NOT NULL, -- 사용자 지정 제목
description TEXT, -- 사용자 지정 설명
original_query TEXT, -- ★ 핵심: 복원용 검색어
full_response TEXT, -- ★ JSON 전체 데이터 (캐싱용)
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
""")
# (4) 검색 결과 테이블 (다운로드용)
cursor.execute("""
CREATE TABLE IF NOT EXISTS search_results (
session_id TEXT PRIMARY KEY,
panel_ids TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
""")
# (5) 검색 결과 캐시 테이블 (UI 복원용)
cursor.execute("""
CREATE TABLE IF NOT EXISTS search_results_cache (
session_id TEXT PRIMARY KEY,
query TEXT NOT NULL,
full_response TEXT NOT NULL, -- JSON string (SearchResponse 전체)
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
""")
conn.commit()
# -------------------------------------------------------
# 4. 생성 확인 (검증)
# -------------------------------------------------------
print("\n🔍 [생성된 테이블 목록 확인]")
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for t in tables:
print(f" - 📜 {t[0]}")
conn.close()
print(f"\n✅ '{db_path.name}' 생성이 완료되었습니다!")
except Exception as e:
print(f"\n❌ [치명적 오류] {e}")
if __name__ == "__main__":
create_tables_v3()