forked from Prateekiiitg56/BizInsight-AI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
372 lines (300 loc) · 10.6 KB
/
Copy pathdatabase.py
File metadata and controls
372 lines (300 loc) · 10.6 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import sqlite3
import logging
import bcrypt
from contextlib import contextmanager
DB_NAME = "bizinsight.db"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@contextmanager
def get_connection():
conn = sqlite3.connect(DB_NAME)
# Enforce SQLite foreign key constraints for all connections
conn.execute("PRAGMA foreign_keys = ON")
try:
yield conn
finally:
conn.close()
def initialize_database():
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
workspace_type TEXT NOT NULL DEFAULT 'personal',
workspace_id TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
review TEXT NOT NULL,
sentiment REAL NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
user_id INTEGER,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_chat_history_session
ON chat_history (session_id, created_at)
""")
conn.commit()
# Workspace support
user_columns = [
row[1] for row in cursor.execute("PRAGMA table_info(users)").fetchall()
]
feedback_columns = [
row[1] for row in cursor.execute("PRAGMA table_info(feedback)").fetchall()
]
if "workspace_type" not in user_columns:
cursor.execute(
"ALTER TABLE users ADD COLUMN workspace_type TEXT NOT NULL DEFAULT 'personal'"
)
if "workspace_id" not in user_columns:
cursor.execute("ALTER TABLE users ADD COLUMN workspace_id TEXT")
if "user_id" not in feedback_columns:
cursor.execute(
"ALTER TABLE feedback ADD COLUMN user_id INTEGER REFERENCES users(id)"
)
conn.commit()
def no_users_exist():
with get_connection() as conn:
cursor = conn.cursor()
count = cursor.execute("SELECT COUNT(*) FROM users").fetchone()[0]
return count == 0
# ─── User Functions ───────────────────────────────────────────────────────────
def create_user(
username, email, password, role="user", workspace_type="personal", workspace_id=None
):
try:
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO users
(
username,
email,
password_hash,
role,
workspace_type,
workspace_id
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(username, email, hashed, role, workspace_type, workspace_id),
)
conn.commit()
return True
except sqlite3.IntegrityError as e:
error_message = str(e).lower()
if "username" in error_message:
return "USERNAME_EXISTS"
if "email" in error_message:
return "EMAIL_EXISTS"
return False # username already taken
except sqlite3.Error as e:
logger.error(f"Create User Error: {e}")
return False
def get_user_by_username(username):
username = (username or "").strip()
if not username:
return None
try:
with get_connection() as conn:
cursor = conn.cursor()
select_query = """
SELECT
id,
username,
email,
password_hash,
role,
workspace_type,
workspace_id
FROM users
WHERE username = ?
"""
cursor.execute(select_query, (username,))
row = cursor.fetchone()
if row:
return {
"id": row[0],
"username": row[1],
"email": row[2],
"password_hash": row[3],
"role": row[4],
"workspace_type": row[5],
"workspace_id": row[6],
}
return None
except sqlite3.Error as e:
logger.error(f"Get User Error: {e}")
return None
def get_user_email(user_id):
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT email FROM users WHERE id=?", (user_id,))
row = cursor.fetchone()
return row[0] if row else None
except sqlite3.Error as e:
logger.error(f"Get Email Error: {e}")
return None
def get_user_workspace(user_id):
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
SELECT workspace_type, workspace_id
FROM users
WHERE id = ?
""",
(user_id,),
)
row = cursor.fetchone()
if row:
return {"workspace_type": row[0], "workspace_id": row[1]}
return None
except sqlite3.Error as e:
logger.error(f"Workspace Fetch Error: {e}")
return None
def get_workspace_feedback(workspace_id):
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
SELECT
f.review,
f.sentiment,
f.created_at
FROM feedback f
INNER JOIN users u
ON f.user_id = u.id
WHERE u.workspace_id = ?
ORDER BY f.created_at DESC
""",
(workspace_id,),
)
return cursor.fetchall()
except sqlite3.Error as e:
logger.error(f"Workspace Fetch Error: {e}")
return []
def verify_password(plain_password, hashed_password):
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
def fetch_all_users():
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT u.id, u.username, u.role, u.created_at,
COUNT(f.id) as review_count
FROM users u
LEFT JOIN feedback f ON f.user_id = u.id
GROUP BY u.id
ORDER BY u.created_at DESC
""")
return cursor.fetchall()
except sqlite3.Error as e:
logger.error(f"Fetch All Users Error: {e}")
return []
def delete_user(user_id):
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM feedback WHERE user_id = ?", (user_id,))
cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))
conn.commit()
return True
except sqlite3.Error as e:
logger.error(f"Delete User Error: {e}")
return False
# ─── Feedback Functions ───────────────────────────────────────────────────────
def insert_feedback(review, sentiment, user_id):
if review is None or str(review).strip() == "":
raise ValueError("Review cannot be empty.")
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO feedback (review, sentiment, user_id) VALUES (?, ?, ?)",
(str(review), sentiment, user_id),
)
conn.commit()
return True
except sqlite3.Error as e:
logger.error(f"Insert Error: {e}")
raise sqlite3.Error(f"Insert Error: {e}")
def insert_feedback_bulk(reviews_data, user_id):
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.executemany(
"INSERT INTO feedback (review, sentiment, user_id) VALUES (?, ?, ?)",
[(review, sentiment, user_id) for review, sentiment in reviews_data],
)
conn.commit()
return True
except sqlite3.Error as e:
logger.error(f"Bulk Insert Error: {e}")
raise sqlite3.Error(f"Bulk Insert Error: {e}")
def fetch_feedback(user_id):
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
SELECT review, sentiment, created_at
FROM feedback
WHERE user_id = ?
ORDER BY created_at DESC, id DESC
""",
(user_id,),
)
return cursor.fetchall()
except sqlite3.Error as e:
logger.error(f"Fetch Error: {e}")
return []
def fetch_all_feedback():
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT f.review, f.sentiment, f.created_at, u.username
FROM feedback f
LEFT JOIN users u ON f.user_id = u.id
ORDER BY f.created_at DESC
""")
return cursor.fetchall()
except sqlite3.Error as e:
logger.error(f"Fetch All Feedback Error: {e}")
return []
def clear_data(user_id):
try:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM feedback WHERE user_id = ?", (user_id,))
conn.commit()
return True
except sqlite3.Error as e:
logger.error(f"Clear Error: {e}")
raise sqlite3.Error(f"Clear Error: {e}")
# Create table when module loads
initialize_database()