Spaces:
Running
Running
Update src/db_connector.py
Browse files- src/db_connector.py +64 -24
src/db_connector.py
CHANGED
|
@@ -8,24 +8,30 @@ class Database:
|
|
| 8 |
def __init__(self):
|
| 9 |
load_dotenv()
|
| 10 |
self.db_uri = os.getenv("DB_URI")
|
|
|
|
| 11 |
|
|
|
|
| 12 |
if not self.db_uri:
|
| 13 |
-
print("โ ๏ธ
|
| 14 |
-
self.db_uri = "sqlite
|
| 15 |
-
|
| 16 |
-
self.parsed = urlparse(self.db_uri)
|
| 17 |
-
|
| 18 |
-
if "sqlite" in self.parsed.scheme:
|
| 19 |
self.type = "sqlite"
|
| 20 |
-
self.db_path = self.
|
| 21 |
-
|
|
|
|
|
|
|
| 22 |
else:
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
def get_connection(self):
|
| 31 |
if self.type == "sqlite":
|
|
@@ -34,14 +40,49 @@ class Database:
|
|
| 34 |
return conn
|
| 35 |
else:
|
| 36 |
return pymysql.connect(
|
| 37 |
-
host=self.host,
|
| 38 |
-
|
| 39 |
-
password=self.password,
|
| 40 |
-
database=self.db_name,
|
| 41 |
-
port=self.port,
|
| 42 |
cursorclass=pymysql.cursors.DictCursor
|
| 43 |
)
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def run_query(self, query):
|
| 46 |
conn = self.get_connection()
|
| 47 |
try:
|
|
@@ -52,8 +93,7 @@ class Database:
|
|
| 52 |
else:
|
| 53 |
cursor = conn.cursor()
|
| 54 |
cursor.execute(query)
|
| 55 |
-
|
| 56 |
-
return items
|
| 57 |
except Exception as e:
|
| 58 |
return [f"Error: {e}"]
|
| 59 |
finally:
|
|
@@ -65,13 +105,13 @@ class Database:
|
|
| 65 |
cursor = conn.cursor()
|
| 66 |
if self.type == "sqlite":
|
| 67 |
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
|
| 68 |
-
|
|
|
|
| 69 |
else:
|
| 70 |
cursor.execute("SHOW TABLES")
|
| 71 |
tables = [list(row.values())[0] for row in cursor.fetchall()]
|
| 72 |
|
| 73 |
-
|
| 74 |
-
print(f"\n๐ FOUND TABLES IN DATABASE: {tables}\n")
|
| 75 |
return tables
|
| 76 |
except Exception as e:
|
| 77 |
print(f"Error fetching tables: {e}")
|
|
|
|
| 8 |
def __init__(self):
|
| 9 |
load_dotenv()
|
| 10 |
self.db_uri = os.getenv("DB_URI")
|
| 11 |
+
self.local_db_path = "./chatbot.db"
|
| 12 |
|
| 13 |
+
# 1. Automatic Fallback to Internal DB
|
| 14 |
if not self.db_uri:
|
| 15 |
+
print("โ ๏ธ DB_URI not found. Using internal 'chatbot.db'...")
|
| 16 |
+
self.db_uri = f"sqlite:///{self.local_db_path}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
self.type = "sqlite"
|
| 18 |
+
self.db_path = self.local_db_path
|
| 19 |
+
|
| 20 |
+
# ๐ AUTO-INIT: Create the data if it doesn't exist
|
| 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"
|
| 27 |
+
self.db_path = parsed.path
|
| 28 |
+
else:
|
| 29 |
+
self.type = "mysql"
|
| 30 |
+
self.host = parsed.hostname
|
| 31 |
+
self.port = parsed.port or 3306
|
| 32 |
+
self.user = parsed.username
|
| 33 |
+
self.password = unquote(parsed.password)
|
| 34 |
+
self.db_name = parsed.path[1:]
|
| 35 |
|
| 36 |
def get_connection(self):
|
| 37 |
if self.type == "sqlite":
|
|
|
|
| 40 |
return conn
|
| 41 |
else:
|
| 42 |
return pymysql.connect(
|
| 43 |
+
host=self.host, user=self.user, password=self.password,
|
| 44 |
+
database=self.db_name, port=self.port,
|
|
|
|
|
|
|
|
|
|
| 45 |
cursorclass=pymysql.cursors.DictCursor
|
| 46 |
)
|
| 47 |
|
| 48 |
+
def _init_sqlite_data(self):
|
| 49 |
+
"""Creates the User's specific schema inside the Space."""
|
| 50 |
+
if os.path.exists(self.local_db_path):
|
| 51 |
+
return # Data already exists
|
| 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 |
+
conn.commit()
|
| 83 |
+
conn.close()
|
| 84 |
+
print("โ
Internal Database Created Successfully!")
|
| 85 |
+
|
| 86 |
def run_query(self, query):
|
| 87 |
conn = self.get_connection()
|
| 88 |
try:
|
|
|
|
| 93 |
else:
|
| 94 |
cursor = conn.cursor()
|
| 95 |
cursor.execute(query)
|
| 96 |
+
return [dict(row) for row in cursor.fetchall()]
|
|
|
|
| 97 |
except Exception as e:
|
| 98 |
return [f"Error: {e}"]
|
| 99 |
finally:
|
|
|
|
| 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 |
+
print(f"\n๐ FOUND TABLES: {tables}\n")
|
|
|
|
| 115 |
return tables
|
| 116 |
except Exception as e:
|
| 117 |
print(f"Error fetching tables: {e}")
|