Spaces:
Sleeping
Sleeping
Update src/db_connector.py
Browse files7 unmodified lines8910111213141516171819202122232425268 unmodified lines3536373839405 unmodified lines46474849505152535455565758596061626364656667686970717273747576777879808182838485868717 unmodified lines10510610710810911011111211311411511611710 unmodified lines1281291301311321337 unmodified linesdef __init__(self):load_dotenv()self.db_uri = os.getenv("DB_URI")self.local_db_path = "./chatbot.db"# 1. Automatic Fallback to Internal DBif not self.db_uri:print("β οΈ DB_URI not found. Using internal 'chatbot.db'...")self.db_uri = f"sqlite:///{self.local_db_path}"self.type = "sqlite"self.db_path = self.local_db_path# π AUTO-INIT: Create the data if it doesn't existself._init_sqlite_data()else:# Parse external DB_URI (if you eventually add a cloud DB)parsed = urlparse(self.db_uri)if "sqlite" in parsed.scheme:self.type = "sqlite"8 unmodified linesdef get_connection(self):if self.type == "sqlite":conn = sqlite3.connect(self.db_path, check_same_thread=False)conn.row_factory = sqlite3.Rowreturn conn5 unmodified lines)def _init_sqlite_data(self):"""Creates the User's specific schema inside the Space."""if os.path.exists(self.local_db_path):return # Data already existsprint("β‘ Initializing internal database with User Data...")conn = sqlite3.connect(self.local_db_path)cursor = conn.cursor()# Your SQL (Adapted for SQLite)commands = ["""CREATE TABLE IF NOT EXISTS employees (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,department TEXT,salary REAL,hire_date TEXT);""","""CREATE TABLE IF NOT EXISTS sales (sale_id INTEGER PRIMARY KEY AUTOINCREMENT,employee_id INTEGER,amount REAL,sale_date TEXT,FOREIGN KEY (employee_id) REFERENCES employees(id));""","INSERT INTO employees (name, department, salary, hire_date) VALUES ('Alice', 'Sales', 70000, '2023-01-15');","INSERT INTO employees (name, department, salary, hire_date) VALUES ('Bob', 'Engineering', 90000, '2022-05-20');","INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 500.00, '2023-06-01');","INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 1200.50, '2023-06-03');"]for cmd in commands:cursor.execute(cmd)conn.commit()conn.close()print("β Internal Database Created Successfully!")def run_query(self, query):conn = self.get_connection()17 unmodified linescursor = conn.cursor()if self.type == "sqlite":cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")# Filter out system tables (sqlite_sequence, etc.)tables = [row[0] for row in cursor.fetchall() if row[0] not in ['sqlite_sequence']]else:cursor.execute("SHOW TABLES")tables = [list(row.values())[0] for row in cursor.fetchall()]print(f"\nπ FOUND TABLES: {tables}\n")return tablesexcept Exception as e:print(f"Error fetching tables: {e}")10 unmodified linescursor.execute(f"PRAGMA table_info({table_name})")rows = cursor.fetchall()for row in rows:col_name = row['name'] if isinstance(row, sqlite3.Row) else row[1]col_type = row['type'] if isinstance(row, sqlite3.Row) else row[2]columns.append(f"{col_name} ({col_type})")7 unmodified lines8910111213141516171819202122232425268 unmodified lines353637383940415 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910017 unmodified lines11811912012112212312412512612712812913010 unmodified lines1411421431441451461477 unmodified linesdef __init__(self):load_dotenv()self.db_uri = os.getenv("DB_URI")# β FIX: Use /tmp/chatbot.db which is ALWAYS writableself.local_db_path = "/tmp/chatbot.db"if not self.db_uri:print(f"β οΈ DB_URI not found. Using internal safe storage: {self.local_db_path}")self.db_uri = f"sqlite:///{self.local_db_path}"self.type = "sqlite"self.db_path = self.local_db_path# Auto-build the user's dataself._init_sqlite_data()else:parsed = urlparse(self.db_uri)if "sqlite" in parsed.scheme:self.type = "sqlite"8 unmodified linesdef get_connection(self):if self.type == "sqlite":# Connect to the Safe Pathconn = sqlite3.connect(self.db_path, check_same_thread=False)conn.row_factory = sqlite3.Rowreturn conn5 unmodified lines)def _init_sqlite_data(self):"""Creates the User's specific schema inside the Safe Temp folder."""# We don't check os.path.exists here because /tmp gets cleared on restart.# We ALWAYS rebuild it to ensure your data is there.print("β‘ Building Database in /tmp/chatbot.db ...")try:conn = sqlite3.connect(self.local_db_path)cursor = conn.cursor()# 1. Clean old data to prevent conflictscursor.execute("DROP TABLE IF EXISTS sales")cursor.execute("DROP TABLE IF EXISTS employees")# 2. Create Your Exact Tablescursor.execute("""CREATE TABLE employees (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,department TEXT,salary REAL,hire_date TEXT)""")cursor.execute("""CREATE TABLE sales (sale_id INTEGER PRIMARY KEY AUTOINCREMENT,employee_id INTEGER,amount REAL,sale_date TEXT,FOREIGN KEY (employee_id) REFERENCES employees(id))""")# 3. Insert Your Datacursor.execute("INSERT INTO employees (name, department, salary, hire_date) VALUES ('Alice', 'Sales', 70000, '2023-01-15')")cursor.execute("INSERT INTO employees (name, department, salary, hire_date) VALUES ('Bob', 'Engineering', 90000, '2022-05-20')")cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 500.00, '2023-06-01')")cursor.execute("INSERT INTO sales (employee_id, amount, sale_date) VALUES (1, 1200.50, '2023-06-03')")conn.commit()print("β Database Built Successfully!")except Exception as e:print(f"β Failed to build database: {e}")finally:if conn: conn.close()def run_query(self, query):conn = self.get_connection()17 unmodified linescursor = conn.cursor()if self.type == "sqlite":cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")tables = [row[0] for row in cursor.fetchall() if row[0] not in ['sqlite_sequence']]else:cursor.execute("SHOW TABLES")tables = [list(row.values())[0] for row in cursor.fetchall()]# Print to logs so we can verifyprint(f"π TABLES IN DB: {tables}")return tablesexcept Exception as e:print(f"Error fetching tables: {e}")10 unmodified linescursor.execute(f"PRAGMA table_info({table_name})")rows = cursor.fetchall()for row in rows:# SQLite PRAGMA returns: (cid, name, type, notnull, dflt_value, pk)col_name = row['name'] if isinstance(row, sqlite3.Row) else row[1]col_type = row['type'] if isinstance(row, sqlite3.Row) else row[2]columns.append(f"{col_name} ({col_type})")
src/db_connector.py+56-42