Sachin21112004 commited on
Commit
20b04f2
·
verified ·
1 Parent(s): 09d073c

Update db.py

Browse files
Files changed (1) hide show
  1. db.py +28 -15
db.py CHANGED
@@ -1,7 +1,8 @@
1
- # db.py (Corrected)
 
2
  import sqlite3
3
  import logging
4
- import json # Import json
5
 
6
  logging.basicConfig(
7
  level=logging.INFO,
@@ -11,11 +12,22 @@ logging.basicConfig(
11
  logger = logging.getLogger(__name__)
12
 
13
  class SessionDB:
14
- def __init__(self, db_path="sessions.db"):
15
- self.conn = sqlite3.connect(db_path, check_same_thread=False)
16
- self.cursor = self.conn.cursor()
17
- self.create_table()
18
-
 
 
 
 
 
 
 
 
 
 
 
19
  def create_table(self):
20
  try:
21
  self.cursor.execute('''
@@ -27,25 +39,26 @@ class SessionDB:
27
  self.conn.commit()
28
  except Exception as e:
29
  logger.error(f"Error creating sessions table: {e}")
30
-
31
  def get_history(self, session_id, max_turns=4):
32
  try:
33
  self.cursor.execute("SELECT history FROM sessions WHERE session_id=?", (session_id,))
34
  result = self.cursor.fetchone()
35
  if result:
36
- # Use json.loads for safety instead of eval()
37
- history = json.loads(result[0])
38
  return history[-max_turns:]
39
  return []
40
  except Exception as e:
41
  logger.error(f"Error retrieving history for session {session_id}: {e}")
42
  return []
43
-
44
  def save_history(self, session_id, history):
45
  try:
46
- # Use json.dumps for safety instead of str()
47
- history_str = json.dumps(history)
48
- self.cursor.execute("INSERT OR REPLACE INTO sessions (session_id, history) VALUES (?, ?)", (session_id, history_str))
 
 
49
  self.conn.commit()
50
  except Exception as e:
51
- logger.error(f"Error saving history for session {session_id}: {e}")
 
1
+ # db.py (Improved)
2
+ import os
3
  import sqlite3
4
  import logging
5
+ import json
6
 
7
  logging.basicConfig(
8
  level=logging.INFO,
 
12
  logger = logging.getLogger(__name__)
13
 
14
  class SessionDB:
15
+ def __init__(self, db_path="db/sessions.db"):
16
+ # Ensure parent folder exists
17
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
18
+
19
+ try:
20
+ self.conn = sqlite3.connect(db_path, check_same_thread=False)
21
+ self.cursor = self.conn.cursor()
22
+ self.create_table()
23
+ logger.info(f"Database initialized at {db_path}")
24
+ except Exception as e:
25
+ logger.error(f"Failed to initialize database at {db_path}: {e}")
26
+ logger.warning("Falling back to in-memory database")
27
+ self.conn = sqlite3.connect(":memory:", check_same_thread=False)
28
+ self.cursor = self.conn.cursor()
29
+ self.create_table()
30
+
31
  def create_table(self):
32
  try:
33
  self.cursor.execute('''
 
39
  self.conn.commit()
40
  except Exception as e:
41
  logger.error(f"Error creating sessions table: {e}")
42
+
43
  def get_history(self, session_id, max_turns=4):
44
  try:
45
  self.cursor.execute("SELECT history FROM sessions WHERE session_id=?", (session_id,))
46
  result = self.cursor.fetchone()
47
  if result:
48
+ history = json.loads(result[0]) # safe parsing
 
49
  return history[-max_turns:]
50
  return []
51
  except Exception as e:
52
  logger.error(f"Error retrieving history for session {session_id}: {e}")
53
  return []
54
+
55
  def save_history(self, session_id, history):
56
  try:
57
+ history_str = json.dumps(history) # safe serialization
58
+ self.cursor.execute(
59
+ "INSERT OR REPLACE INTO sessions (session_id, history) VALUES (?, ?)",
60
+ (session_id, history_str)
61
+ )
62
  self.conn.commit()
63
  except Exception as e:
64
+ logger.error(f"Error saving history for session {session_id}: {e}")