-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
90 lines (71 loc) · 2.19 KB
/
db.py
File metadata and controls
90 lines (71 loc) · 2.19 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
import sqlite3
from pathlib import Path
DB_PATH = Path("employees.db")
def get_connection():
return sqlite3.connect(DB_PATH)
def init_db():
"""Create database and tables if they don't exist."""
conn = get_connection()
cursor = conn.cursor()
# Employees table
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
department TEXT NOT NULL,
title TEXT
)
""")
# Salaries table (FK to employees.id)
cursor.execute("""
CREATE TABLE IF NOT EXISTS salaries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
employee_id INTEGER NOT NULL,
salary REAL NOT NULL,
FOREIGN KEY (employee_id) REFERENCES employees(id)
)
""")
conn.commit()
conn.close()
def fill_db():
conn = get_connection()
cursor = conn.cursor()
# Seed employees
cursor.execute("SELECT COUNT(*) FROM employees")
emp_count = cursor.fetchone()[0]
if emp_count == 0:
cursor.executemany("""
INSERT INTO employees (name, department, title)
VALUES (?, ?, ?)
""", [
("Alice Johnson", "Sales", "Account Manager"),
("Bob Smith", "Sales", "Sales Rep"),
("Carol White", "Engineering", "Backend Developer"),
("David Brown", "Engineering", "Frontend Developer"),
("Eve Davis", "HR", "HR Manager")
])
# Seed salaries
cursor.execute("SELECT COUNT(*) FROM salaries")
sal_count = cursor.fetchone()[0]
if sal_count == 0:
cursor.executemany("""
INSERT INTO salaries (employee_id, salary)
VALUES (?, ?)
""", [
(1, 75000),
(2, 65000),
(3, 95000),
(4, 90000),
(5, 70000)
])
conn.commit()
conn.close()
def query_db(llm_query):
conn = get_connection()
cursor = conn.cursor()
cursor.execute(llm_query)
rows = cursor.fetchall()
columns = [description[0] for description in cursor.description]
results = [dict(zip(columns, row)) for row in rows]
conn.close()
return results