Spaces:
Sleeping
Sleeping
Update src/db_connector.py
Browse files- src/db_connector.py +42 -65
src/db_connector.py
CHANGED
|
@@ -7,40 +7,25 @@ from urllib.parse import urlparse, unquote
|
|
| 7 |
class Database:
|
| 8 |
def __init__(self):
|
| 9 |
load_dotenv()
|
| 10 |
-
self.db_uri = os.getenv("DB_URI")
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
self.type = "sqlite"
|
| 20 |
-
self.db_path = self.local_db_path
|
| 21 |
-
|
| 22 |
-
# Auto-build the user's data every time
|
| 23 |
-
self._init_sqlite_data()
|
| 24 |
-
else:
|
| 25 |
-
parsed = urlparse(self.db_uri)
|
| 26 |
-
if "sqlite" in parsed.scheme:
|
| 27 |
-
self.type = "sqlite"
|
| 28 |
-
self.db_path = parsed.path
|
| 29 |
-
else:
|
| 30 |
-
self.type = "mysql"
|
| 31 |
-
self.host = parsed.hostname
|
| 32 |
-
self.port = parsed.port or 3306
|
| 33 |
-
self.user = parsed.username
|
| 34 |
-
self.password = unquote(parsed.password)
|
| 35 |
-
self.db_name = parsed.path[1:]
|
| 36 |
|
| 37 |
def get_connection(self):
|
| 38 |
if self.type == "sqlite":
|
| 39 |
-
# Connect to the
|
| 40 |
conn = sqlite3.connect(self.db_path, check_same_thread=False)
|
| 41 |
conn.row_factory = sqlite3.Row
|
| 42 |
return conn
|
| 43 |
else:
|
|
|
|
| 44 |
return pymysql.connect(
|
| 45 |
host=self.host, user=self.user, password=self.password,
|
| 46 |
database=self.db_name, port=self.port,
|
|
@@ -48,20 +33,16 @@ class Database:
|
|
| 48 |
)
|
| 49 |
|
| 50 |
def _init_sqlite_data(self):
|
| 51 |
-
"""
|
| 52 |
-
# We REBUILD it on every startup to ensure the schema matches your code.
|
| 53 |
-
print("β‘ Building Database in /tmp/chatbot.db ...")
|
| 54 |
-
|
| 55 |
-
conn = None
|
| 56 |
try:
|
| 57 |
-
conn = sqlite3.connect(self.
|
| 58 |
cursor = conn.cursor()
|
| 59 |
|
| 60 |
-
# 1.
|
| 61 |
cursor.execute("DROP TABLE IF EXISTS sales")
|
| 62 |
cursor.execute("DROP TABLE IF EXISTS employees")
|
| 63 |
-
|
| 64 |
-
# 2. Create
|
| 65 |
cursor.execute("""
|
| 66 |
CREATE TABLE employees (
|
| 67 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -72,6 +53,7 @@ class Database:
|
|
| 72 |
)
|
| 73 |
""")
|
| 74 |
|
|
|
|
| 75 |
cursor.execute("""
|
| 76 |
CREATE TABLE sales (
|
| 77 |
sale_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -82,32 +64,37 @@ class Database:
|
|
| 82 |
)
|
| 83 |
""")
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 500.00, '2023-06-01')")
|
| 90 |
cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 1200.50, '2023-06-03')")
|
| 91 |
|
| 92 |
conn.commit()
|
| 93 |
-
print("β
Database Built Successfully!")
|
| 94 |
|
| 95 |
except Exception as e:
|
| 96 |
-
print(f"β
|
| 97 |
finally:
|
| 98 |
if conn: conn.close()
|
| 99 |
|
| 100 |
def run_query(self, query):
|
| 101 |
conn = self.get_connection()
|
| 102 |
try:
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
else:
|
| 108 |
-
cursor = conn.cursor()
|
| 109 |
-
cursor.execute(query)
|
| 110 |
return [dict(row) for row in cursor.fetchall()]
|
|
|
|
|
|
|
| 111 |
except Exception as e:
|
| 112 |
return [f"Error: {e}"]
|
| 113 |
finally:
|
|
@@ -117,14 +104,10 @@ class Database:
|
|
| 117 |
conn = self.get_connection()
|
| 118 |
try:
|
| 119 |
cursor = conn.cursor()
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
tables = [row[0] for row in cursor.fetchall() if row[0] not in ['sqlite_sequence']]
|
| 123 |
-
else:
|
| 124 |
-
cursor.execute("SHOW TABLES")
|
| 125 |
-
tables = [list(row.values())[0] for row in cursor.fetchall()]
|
| 126 |
|
| 127 |
-
print(f"π TABLES
|
| 128 |
return tables
|
| 129 |
except Exception as e:
|
| 130 |
print(f"Error fetching tables: {e}")
|
|
@@ -137,18 +120,12 @@ class Database:
|
|
| 137 |
columns = []
|
| 138 |
try:
|
| 139 |
cursor = conn.cursor()
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
columns.append(f"{col_name} ({col_type})")
|
| 147 |
-
else:
|
| 148 |
-
cursor.execute(f"DESCRIBE {table_name}")
|
| 149 |
-
rows = cursor.fetchall()
|
| 150 |
-
for row in rows:
|
| 151 |
-
columns.append(f"{row['Field']} ({row['Type']})")
|
| 152 |
return columns
|
| 153 |
except Exception as e:
|
| 154 |
return []
|
|
|
|
| 7 |
class Database:
|
| 8 |
def __init__(self):
|
| 9 |
load_dotenv()
|
|
|
|
| 10 |
|
| 11 |
+
# π FORCE SAFE PATH: We ignore .env settings for SQLite to prevent permission errors
|
| 12 |
+
# We use /tmp/ which is ALWAYS writable on Hugging Face/Linux
|
| 13 |
+
self.db_path = "/tmp/chatbot_v2.db"
|
| 14 |
+
self.type = "sqlite"
|
| 15 |
|
| 16 |
+
print(f" β‘ DATABASE PATH FORCED: {self.db_path}")
|
| 17 |
+
|
| 18 |
+
# Always rebuild the demo data to ensure it exists
|
| 19 |
+
self._init_sqlite_data()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def get_connection(self):
|
| 22 |
if self.type == "sqlite":
|
| 23 |
+
# Connect to the safe temp file
|
| 24 |
conn = sqlite3.connect(self.db_path, check_same_thread=False)
|
| 25 |
conn.row_factory = sqlite3.Row
|
| 26 |
return conn
|
| 27 |
else:
|
| 28 |
+
# Fallback for MySQL (if you ever switch back)
|
| 29 |
return pymysql.connect(
|
| 30 |
host=self.host, user=self.user, password=self.password,
|
| 31 |
database=self.db_name, port=self.port,
|
|
|
|
| 33 |
)
|
| 34 |
|
| 35 |
def _init_sqlite_data(self):
|
| 36 |
+
"""Forces creation of a fresh database with your data."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
+
conn = sqlite3.connect(self.db_path)
|
| 39 |
cursor = conn.cursor()
|
| 40 |
|
| 41 |
+
# 1. Wipe clean to remove old errors
|
| 42 |
cursor.execute("DROP TABLE IF EXISTS sales")
|
| 43 |
cursor.execute("DROP TABLE IF EXISTS employees")
|
| 44 |
+
|
| 45 |
+
# 2. Create 'employees' (Lowercase, Plural)
|
| 46 |
cursor.execute("""
|
| 47 |
CREATE TABLE employees (
|
| 48 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
| 53 |
)
|
| 54 |
""")
|
| 55 |
|
| 56 |
+
# 3. Create 'sales'
|
| 57 |
cursor.execute("""
|
| 58 |
CREATE TABLE sales (
|
| 59 |
sale_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
| 64 |
)
|
| 65 |
""")
|
| 66 |
|
| 67 |
+
# 4. Insert Data
|
| 68 |
+
data_employees = [
|
| 69 |
+
('Alice', 'Sales', 70000, '2023-01-15'),
|
| 70 |
+
('Bob', 'Engineering', 90000, '2022-05-20'),
|
| 71 |
+
('Charlie', 'Marketing', 60000, '2023-03-10'),
|
| 72 |
+
('David', 'Engineering', 95000, '2021-11-05'),
|
| 73 |
+
('Eve', 'Sales', 72000, '2023-02-28')
|
| 74 |
+
]
|
| 75 |
+
cursor.executemany("INSERT INTO employees (name, department, salary, hire_date) VALUES (?, ?, ?, ?)", data_employees)
|
| 76 |
|
| 77 |
cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 500.00, '2023-06-01')")
|
| 78 |
cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 1200.50, '2023-06-03')")
|
| 79 |
|
| 80 |
conn.commit()
|
| 81 |
+
print(" β
Internal Database & Data Built Successfully!")
|
| 82 |
|
| 83 |
except Exception as e:
|
| 84 |
+
print(f" β FATAL DB ERROR: {e}")
|
| 85 |
finally:
|
| 86 |
if conn: conn.close()
|
| 87 |
|
| 88 |
def run_query(self, query):
|
| 89 |
conn = self.get_connection()
|
| 90 |
try:
|
| 91 |
+
cursor = conn.cursor()
|
| 92 |
+
cursor.execute(query)
|
| 93 |
+
# Handle different cursor types
|
| 94 |
+
if self.type == "sqlite":
|
|
|
|
|
|
|
|
|
|
| 95 |
return [dict(row) for row in cursor.fetchall()]
|
| 96 |
+
else:
|
| 97 |
+
return cursor.fetchall()
|
| 98 |
except Exception as e:
|
| 99 |
return [f"Error: {e}"]
|
| 100 |
finally:
|
|
|
|
| 104 |
conn = self.get_connection()
|
| 105 |
try:
|
| 106 |
cursor = conn.cursor()
|
| 107 |
+
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
|
| 108 |
+
tables = [row[0] for row in cursor.fetchall() if row[0] != 'sqlite_sequence']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
print(f" π TABLES FOUND: {tables}")
|
| 111 |
return tables
|
| 112 |
except Exception as e:
|
| 113 |
print(f"Error fetching tables: {e}")
|
|
|
|
| 120 |
columns = []
|
| 121 |
try:
|
| 122 |
cursor = conn.cursor()
|
| 123 |
+
cursor.execute(f"PRAGMA table_info({table_name})")
|
| 124 |
+
rows = cursor.fetchall()
|
| 125 |
+
for row in rows:
|
| 126 |
+
col_name = row['name'] if isinstance(row, sqlite3.Row) else row[1]
|
| 127 |
+
col_type = row['type'] if isinstance(row, sqlite3.Row) else row[2]
|
| 128 |
+
columns.append(f"{col_name} ({col_type})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
return columns
|
| 130 |
except Exception as e:
|
| 131 |
return []
|