mugunthjhs commited on
Commit
77c3f13
·
verified ·
1 Parent(s): e55a400

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +29 -16
database.py CHANGED
@@ -1,12 +1,23 @@
1
  import sqlite3
 
2
  from langchain_community.utilities.sql_database import SQLDatabase
3
 
4
- DB_FILENAME = "tasks.db"
 
5
  DB_PATH_URI = f"sqlite:///{DB_FILENAME}"
6
 
 
7
  def create_db_and_table():
 
 
 
 
 
 
 
8
  conn = sqlite3.connect(DB_FILENAME)
9
  cursor = conn.cursor()
 
10
  cursor.execute("""
11
  CREATE TABLE IF NOT EXISTS tasks (
12
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -29,14 +40,18 @@ def create_db_and_table():
29
  print(f"Warning: Could not create unique index idx_unq_user_task, it might exist or conflict: {e}")
30
  conn.commit()
31
  conn.close()
 
 
32
 
 
 
33
  def get_db_info():
34
  db = SQLDatabase.from_uri(DB_PATH_URI, include_tables=['tasks'])
35
  return db.get_table_info()
36
 
37
  def get_task_by_id(task_id: int, user_email: str):
38
  query = "SELECT id, task_name, status, category, due_date, due_time, created_at FROM tasks WHERE id = ? AND user_email = ?"
39
- conn = sqlite3.connect(DB_FILENAME)
40
  cursor = conn.cursor()
41
  try:
42
  cursor.execute(query, (task_id, user_email))
@@ -52,7 +67,7 @@ def get_task_by_id(task_id: int, user_email: str):
52
  conn.close()
53
 
54
  def execute_select_query(query: str, params: tuple = None):
55
- conn = sqlite3.connect(DB_FILENAME)
56
  cursor = conn.cursor()
57
  try:
58
  cursor.execute(query, params or ())
@@ -66,7 +81,7 @@ def execute_select_query(query: str, params: tuple = None):
66
  conn.close()
67
 
68
  def execute_dml_query(query: str, params: tuple = None):
69
- conn = sqlite3.connect(DB_FILENAME)
70
  cursor = conn.cursor()
71
  is_insert = query.strip().upper().startswith("INSERT")
72
  try:
@@ -75,21 +90,19 @@ def execute_dml_query(query: str, params: tuple = None):
75
  if is_insert:
76
  return cursor.lastrowid
77
  return cursor.rowcount
78
-
79
- except sqlite3.IntegrityError as e:
80
- error_code = getattr(e, 'sqlite_errorcode', None)
81
- if not error_code and hasattr(e, 'args') and len(e.args) > 0:
82
- if "UNIQUE constraint failed" in str(e.args[0]).upper():
83
- error_code = 2067
84
  if error_code == 2067 or error_code == 1555 or \
85
  (isinstance(e, sqlite3.IntegrityError) and "UNIQUE constraint failed" in str(e).upper()):
86
- raise ValueError(f"Task likely already exists with the same name, due date, and time. (Details: {e})")
87
  else:
88
- print(f"Unhandled IntegrityError executing DML query: {query}\nCode: {error_code}, Error: {e}")
89
- raise
90
-
91
  except sqlite3.Error as e:
92
- print(f"General SQLite error executing DML query: {query}\n{e}")
93
  raise
94
  finally:
95
- conn.close()
 
1
  import sqlite3
2
+ import os
3
  from langchain_community.utilities.sql_database import SQLDatabase
4
 
5
+ PERSISTENT_STORAGE_PATH = os.environ.get("HF_PERSISTENT_STORAGE_PATH", "/data")
6
+ DB_FILENAME = os.path.join(PERSISTENT_STORAGE_PATH, "tasks.db")
7
  DB_PATH_URI = f"sqlite:///{DB_FILENAME}"
8
 
9
+
10
  def create_db_and_table():
11
+ """Creates the SQLite database and tasks table if they don't exist."""
12
+
13
+ os.makedirs(os.path.dirname(DB_FILENAME), exist_ok=True)
14
+ print(f"Database directory {os.path.dirname(DB_FILENAME)} ensured.")
15
+ except OSError as e:
16
+ print(f"Error creating database directory {os.path.dirname(DB_FILENAME)}: {e}")
17
+
18
  conn = sqlite3.connect(DB_FILENAME)
19
  cursor = conn.cursor()
20
+
21
  cursor.execute("""
22
  CREATE TABLE IF NOT EXISTS tasks (
23
  id INTEGER PRIMARY KEY AUTOINCREMENT,
 
40
  print(f"Warning: Could not create unique index idx_unq_user_task, it might exist or conflict: {e}")
41
  conn.commit()
42
  conn.close()
43
+ print(f"✅ Database and table checked/created at {DB_FILENAME}.")
44
+
45
 
46
+ # ... (rest of your database.py, e.g., get_db_info, execute_select_query, etc.) ...
47
+ # All functions like `sqlite3.connect(DB_FILENAME)` will now use the path in persistent storage.
48
  def get_db_info():
49
  db = SQLDatabase.from_uri(DB_PATH_URI, include_tables=['tasks'])
50
  return db.get_table_info()
51
 
52
  def get_task_by_id(task_id: int, user_email: str):
53
  query = "SELECT id, task_name, status, category, due_date, due_time, created_at FROM tasks WHERE id = ? AND user_email = ?"
54
+ conn = sqlite3.connect(DB_FILENAME) # Uses persistent path
55
  cursor = conn.cursor()
56
  try:
57
  cursor.execute(query, (task_id, user_email))
 
67
  conn.close()
68
 
69
  def execute_select_query(query: str, params: tuple = None):
70
+ conn = sqlite3.connect(DB_FILENAME) # Uses persistent path
71
  cursor = conn.cursor()
72
  try:
73
  cursor.execute(query, params or ())
 
81
  conn.close()
82
 
83
  def execute_dml_query(query: str, params: tuple = None):
84
+ conn = sqlite3.connect(DB_FILENAME) # Uses persistent path
85
  cursor = conn.cursor()
86
  is_insert = query.strip().upper().startswith("INSERT")
87
  try:
 
90
  if is_insert:
91
  return cursor.lastrowid
92
  return cursor.rowcount
93
+ except sqlite3.IntegrityError as e:
94
+ error_code = getattr(e, 'sqlite_errorcode', None)
95
+ if not error_code and hasattr(e, 'args') and len(e.args) > 0:
96
+ if "UNIQUE constraint failed" in str(e.args[0]).upper():
97
+ error_code = 2067
 
98
  if error_code == 2067 or error_code == 1555 or \
99
  (isinstance(e, sqlite3.IntegrityError) and "UNIQUE constraint failed" in str(e).upper()):
100
+ raise ValueError(f"Task likely already exists. (Details: {e})")
101
  else:
102
+ print(f"Unhandled IntegrityError: {query}\nCode: {error_code}, Error: {e}")
103
+ raise
 
104
  except sqlite3.Error as e:
105
+ print(f"General SQLite error: {query}\n{e}")
106
  raise
107
  finally:
108
+ conn.close()