Spaces:
Sleeping
Sleeping
Update src/db_connector.py
Browse files- src/db_connector.py +56 -42
src/db_connector.py
CHANGED
|
@@ -8,19 +8,19 @@ class Database:
|
|
| 8 |
def __init__(self):
|
| 9 |
load_dotenv()
|
| 10 |
self.db_uri = os.getenv("DB_URI")
|
| 11 |
-
self.local_db_path = "./chatbot.db"
|
| 12 |
|
| 13 |
-
#
|
|
|
|
|
|
|
| 14 |
if not self.db_uri:
|
| 15 |
-
print("⚠️ DB_URI not found. Using internal
|
| 16 |
self.db_uri = f"sqlite:///{self.local_db_path}"
|
| 17 |
self.type = "sqlite"
|
| 18 |
self.db_path = self.local_db_path
|
| 19 |
|
| 20 |
-
#
|
| 21 |
self._init_sqlite_data()
|
| 22 |
else:
|
| 23 |
-
# Parse external DB_URI (if you eventually add a cloud DB)
|
| 24 |
parsed = urlparse(self.db_uri)
|
| 25 |
if "sqlite" in parsed.scheme:
|
| 26 |
self.type = "sqlite"
|
|
@@ -35,6 +35,7 @@ class Database:
|
|
| 35 |
|
| 36 |
def get_connection(self):
|
| 37 |
if self.type == "sqlite":
|
|
|
|
| 38 |
conn = sqlite3.connect(self.db_path, check_same_thread=False)
|
| 39 |
conn.row_factory = sqlite3.Row
|
| 40 |
return conn
|
|
@@ -46,42 +47,54 @@ class Database:
|
|
| 46 |
)
|
| 47 |
|
| 48 |
def _init_sqlite_data(self):
|
| 49 |
-
"""Creates the User's specific schema inside the
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
print("⚡ Initializing internal database with User Data...")
|
| 54 |
-
conn = sqlite3.connect(self.local_db_path)
|
| 55 |
-
cursor = conn.cursor()
|
| 56 |
-
|
| 57 |
-
# Your SQL (Adapted for SQLite)
|
| 58 |
-
commands = [
|
| 59 |
-
"""CREATE TABLE IF NOT EXISTS employees (
|
| 60 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 61 |
-
name TEXT,
|
| 62 |
-
department TEXT,
|
| 63 |
-
salary REAL,
|
| 64 |
-
hire_date TEXT
|
| 65 |
-
);""",
|
| 66 |
-
"""CREATE TABLE IF NOT EXISTS sales (
|
| 67 |
-
sale_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 68 |
-
employee_id INTEGER,
|
| 69 |
-
amount REAL,
|
| 70 |
-
sale_date TEXT,
|
| 71 |
-
FOREIGN KEY (employee_id) REFERENCES employees(id)
|
| 72 |
-
);""",
|
| 73 |
-
"INSERT INTO employees (name, department, salary, hire_date) VALUES ('Alice', 'Sales', 70000, '2023-01-15');",
|
| 74 |
-
"INSERT INTO employees (name, department, salary, hire_date) VALUES ('Bob', 'Engineering', 90000, '2022-05-20');",
|
| 75 |
-
"INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 500.00, '2023-06-01');",
|
| 76 |
-
"INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 1200.50, '2023-06-03');"
|
| 77 |
-
]
|
| 78 |
-
|
| 79 |
-
for cmd in commands:
|
| 80 |
-
cursor.execute(cmd)
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
def run_query(self, query):
|
| 87 |
conn = self.get_connection()
|
|
@@ -105,13 +118,13 @@ class Database:
|
|
| 105 |
cursor = conn.cursor()
|
| 106 |
if self.type == "sqlite":
|
| 107 |
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
|
| 108 |
-
# Filter out system tables (sqlite_sequence, etc.)
|
| 109 |
tables = [row[0] for row in cursor.fetchall() if row[0] not in ['sqlite_sequence']]
|
| 110 |
else:
|
| 111 |
cursor.execute("SHOW TABLES")
|
| 112 |
tables = [list(row.values())[0] for row in cursor.fetchall()]
|
| 113 |
|
| 114 |
-
|
|
|
|
| 115 |
return tables
|
| 116 |
except Exception as e:
|
| 117 |
print(f"Error fetching tables: {e}")
|
|
@@ -128,6 +141,7 @@ class Database:
|
|
| 128 |
cursor.execute(f"PRAGMA table_info({table_name})")
|
| 129 |
rows = cursor.fetchall()
|
| 130 |
for row in rows:
|
|
|
|
| 131 |
col_name = row['name'] if isinstance(row, sqlite3.Row) else row[1]
|
| 132 |
col_type = row['type'] if isinstance(row, sqlite3.Row) else row[2]
|
| 133 |
columns.append(f"{col_name} ({col_type})")
|
|
|
|
| 8 |
def __init__(self):
|
| 9 |
load_dotenv()
|
| 10 |
self.db_uri = os.getenv("DB_URI")
|
|
|
|
| 11 |
|
| 12 |
+
# ✅ FIX: Use /tmp/chatbot.db which is ALWAYS writable
|
| 13 |
+
self.local_db_path = "/tmp/chatbot.db"
|
| 14 |
+
|
| 15 |
if not self.db_uri:
|
| 16 |
+
print(f"⚠️ DB_URI not found. Using internal safe storage: {self.local_db_path}")
|
| 17 |
self.db_uri = f"sqlite:///{self.local_db_path}"
|
| 18 |
self.type = "sqlite"
|
| 19 |
self.db_path = self.local_db_path
|
| 20 |
|
| 21 |
+
# Auto-build the user's data
|
| 22 |
self._init_sqlite_data()
|
| 23 |
else:
|
|
|
|
| 24 |
parsed = urlparse(self.db_uri)
|
| 25 |
if "sqlite" in parsed.scheme:
|
| 26 |
self.type = "sqlite"
|
|
|
|
| 35 |
|
| 36 |
def get_connection(self):
|
| 37 |
if self.type == "sqlite":
|
| 38 |
+
# Connect to the Safe Path
|
| 39 |
conn = sqlite3.connect(self.db_path, check_same_thread=False)
|
| 40 |
conn.row_factory = sqlite3.Row
|
| 41 |
return conn
|
|
|
|
| 47 |
)
|
| 48 |
|
| 49 |
def _init_sqlite_data(self):
|
| 50 |
+
"""Creates the User's specific schema inside the Safe Temp folder."""
|
| 51 |
+
# We don't check os.path.exists here because /tmp gets cleared on restart.
|
| 52 |
+
# We ALWAYS rebuild it to ensure your data is there.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
print("⚡ Building Database in /tmp/chatbot.db ...")
|
| 55 |
+
try:
|
| 56 |
+
conn = sqlite3.connect(self.local_db_path)
|
| 57 |
+
cursor = conn.cursor()
|
| 58 |
+
|
| 59 |
+
# 1. Clean old data to prevent conflicts
|
| 60 |
+
cursor.execute("DROP TABLE IF EXISTS sales")
|
| 61 |
+
cursor.execute("DROP TABLE IF EXISTS employees")
|
| 62 |
+
|
| 63 |
+
# 2. Create Your Exact Tables
|
| 64 |
+
cursor.execute("""
|
| 65 |
+
CREATE TABLE employees (
|
| 66 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 67 |
+
name TEXT,
|
| 68 |
+
department TEXT,
|
| 69 |
+
salary REAL,
|
| 70 |
+
hire_date TEXT
|
| 71 |
+
)
|
| 72 |
+
""")
|
| 73 |
+
|
| 74 |
+
cursor.execute("""
|
| 75 |
+
CREATE TABLE sales (
|
| 76 |
+
sale_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 77 |
+
employee_id INTEGER,
|
| 78 |
+
amount REAL,
|
| 79 |
+
sale_date TEXT,
|
| 80 |
+
FOREIGN KEY (employee_id) REFERENCES employees(id)
|
| 81 |
+
)
|
| 82 |
+
""")
|
| 83 |
+
|
| 84 |
+
# 3. Insert Your Data
|
| 85 |
+
cursor.execute("INSERT INTO employees (name, department, salary, hire_date) VALUES ('Alice', 'Sales', 70000, '2023-01-15')")
|
| 86 |
+
cursor.execute("INSERT INTO employees (name, department, salary, hire_date) VALUES ('Bob', 'Engineering', 90000, '2022-05-20')")
|
| 87 |
+
|
| 88 |
+
cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 500.00, '2023-06-01')")
|
| 89 |
+
cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 1200.50, '2023-06-03')")
|
| 90 |
+
|
| 91 |
+
conn.commit()
|
| 92 |
+
print("✅ Database Built Successfully!")
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"❌ Failed to build database: {e}")
|
| 96 |
+
finally:
|
| 97 |
+
if conn: conn.close()
|
| 98 |
|
| 99 |
def run_query(self, query):
|
| 100 |
conn = self.get_connection()
|
|
|
|
| 118 |
cursor = conn.cursor()
|
| 119 |
if self.type == "sqlite":
|
| 120 |
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
|
|
|
|
| 121 |
tables = [row[0] for row in cursor.fetchall() if row[0] not in ['sqlite_sequence']]
|
| 122 |
else:
|
| 123 |
cursor.execute("SHOW TABLES")
|
| 124 |
tables = [list(row.values())[0] for row in cursor.fetchall()]
|
| 125 |
|
| 126 |
+
# Print to logs so we can verify
|
| 127 |
+
print(f"🔍 TABLES IN DB: {tables}")
|
| 128 |
return tables
|
| 129 |
except Exception as e:
|
| 130 |
print(f"Error fetching tables: {e}")
|
|
|
|
| 141 |
cursor.execute(f"PRAGMA table_info({table_name})")
|
| 142 |
rows = cursor.fetchall()
|
| 143 |
for row in rows:
|
| 144 |
+
# SQLite PRAGMA returns: (cid, name, type, notnull, dflt_value, pk)
|
| 145 |
col_name = row['name'] if isinstance(row, sqlite3.Row) else row[1]
|
| 146 |
col_type = row['type'] if isinstance(row, sqlite3.Row) else row[2]
|
| 147 |
columns.append(f"{col_name} ({col_type})")
|