Spaces:
Sleeping
Sleeping
Update src/db_connector.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import pymysqlimport osfrom dotenv import load_dotenvfrom urllib.parse import urlparse, unquote# ✅ FIX 1: Class renamed to 'Database' (matches api_server.py)class Database:def __init__(self):load_dotenv()db_uri = os.getenv("DB_URI")if not db_uri:raise ValueError("❌ DB_URI is missing from .env file")parsed = urlparse(db_uri)self.host = parsed.hostnameself.port = parsed.port or 3306self.user = parsed.usernameself.password = unquote(parsed.password)self.db_name = parsed.path[1:]def get_connection(self):return pymysql.connect(host=self.host,user=self.user,password=self.password,database=self.db_name,port=self.port,cursorclass=pymysql.cursors.DictCursor)# ✅ FIX 2: Method renamed to 'run_query' (matches api_server.py)def run_query(self, query):conn = self.get_connection()try:with conn.cursor() as cursor:cursor.execute(query)return cursor.fetchall()except Exception as e:return [f"Error: {e}"]finally:conn.close()def get_tables(self):"""Returns a list of all table names."""conn = self.get_connection()try:with conn.cursor() as cursor:cursor.execute("SHOW TABLES")return [list(row.values())[0] for row in cursor.fetchall()]except Exception as e:return []finally:conn.close()def get_table_schema(self, table_name):"""Returns column details for a specific table."""conn = self.get_connection()try:with conn.cursor() as cursor:cursor.execute(f"DESCRIBE {table_name}")columns = []for row in cursor.fetchall():columns.append(f"{row['Field']} ({row['Type']})")return columnsexcept Exception:return []finally:conn.close()# ✅ FIX 3: Added 'get_schema()' (no args) for the RAG systemdef get_schema(self):"""Generates a full text schema of the database for the AI."""tables = self.get_tables()schema_text = ""for table in tables:columns = self.get_table_schema(table)schema_text += f"Table: {table}\nColumns:\n"for col in columns:schema_text += f" - {col}\n"schema_text += "\n"return schema_text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134import pymysqlimport sqlite3import osfrom dotenv import load_dotenvfrom urllib.parse import urlparse, unquoteclass Database:def __init__(self):load_dotenv()self.db_uri = os.getenv("DB_URI")# 🛡️ SAFETY FIX: If DB_URI is missing, default to a local SQLite demo file# This prevents the "NoneType is not iterable" crash on Hugging Faceif not self.db_uri:print("⚠️ WARNING: DB_URI not found. Defaulting to 'sqlite:///./demo.db'")self.db_uri = "sqlite:///./demo.db"self.parsed = urlparse(self.db_uri)# Determine Database Typeif "sqlite" in self.parsed.scheme:self.type = "sqlite"# Extract path (remove 'sqlite:///')self.db_path = self.parsed.path if self.parsed.path else "./demo.db"# Fix absolute paths if neededif self.db_path.startswith("/."): self.db_path = self.db_path[1:]else:self.type = "mysql"self.host = self.parsed.hostnameself.port = self.parsed.port or 3306self.user = self.parsed.usernameself.password = unquote(self.parsed.password)self.db_name = self.parsed.path[1:]def get_connection(self):if self.type == "sqlite":# Connect to SQLite Fileconn = sqlite3.connect(self.db_path, check_same_thread=False)conn.row_factory = sqlite3.Row # Allows accessing columns by namereturn connelse:# Connect to MySQL Serverreturn pymysql.connect(host=self.host,user=self.user,password=self.password,database=self.db_name,port=self.port,cursorclass=pymysql.cursors.DictCursor)def run_query(self, query):conn = self.get_connection()try:# MySQL Logicif self.type == "mysql":with conn.cursor() as cursor:cursor.execute(query)return cursor.fetchall()# SQLite Logicelse:cursor = conn.cursor()cursor.execute(query)# Convert SQLite rows to list of dicts to match MySQL formatitems = [dict(row) for row in cursor.fetchall()]return itemsexcept Exception as e:return [f"Error: {e}"]finally:conn.close()def get_tables(self):"""Returns a list of all table names (supports both SQLite & MySQL)."""conn = self.get_connection()try:cursor = conn.cursor()if self.type == "sqlite":cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")return [row[0] for row in cursor.fetchall()] # row[0] for standard cursor, row['name'] for Row factoryelse:cursor.execute("SHOW TABLES")return [list(row.values())[0] for row in cursor.fetchall()]except Exception as e:print(f"Error fetching tables: {e}")return []finally:conn.close()def get_table_schema(self, table_name):"""Returns column details for a specific table."""conn = self.get_connection()columns = []try:cursor = conn.cursor()if self.type == "sqlite":# SQLite Schema Querycursor.execute(f"PRAGMA table_info({table_name})")rows = cursor.fetchall()# Row format: (cid, name, type, notnull, dflt_value, pk)for row in rows:# Handle both tuple and Row object accesscol_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})")else:# MySQL Schema Querycursor.execute(f"DESCRIBE {table_name}")rows = cursor.fetchall()for row in rows:columns.append(f"{row['Field']} ({row['Type']})")return columnsexcept Exception as e:print(f"Error fetching schema for {table_name}: {e}")return []finally:conn.close()def get_schema(self):"""Generates a full text schema of the database for the AI."""tables = self.get_tables()schema_text = ""for table in tables:columns = self.get_table_schema(table)schema_text += f"Table: {table}\nColumns:\n"for col in columns:schema_text += f" - {col}\n"schema_text += "\n"return schema_text
src/db_connector.py+133-83