Spaces:
Sleeping
Sleeping
Update src/db_connector.py
Browse files8 unmodified lines9101112131415161718192021222324252627285 unmodified lines3435363738394041424344456 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586871 unmodified line89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331348 unmodified linesload_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"5 unmodified linesdef 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,6 unmodified linesdef 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 []1 unmodified lineconn.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_text8 unmodified lines910111213141516171819202122235 unmodified lines293031323334353637386 unmodified lines454647484950515253545556575859606162636465666768697071727374757677781 unmodified line80818283848586878889909192939495969798991001011021031041051061071081091101111121131148 unmodified linesload_dotenv()self.db_uri = os.getenv("DB_URI")if 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)if "sqlite" in self.parsed.scheme:self.type = "sqlite"self.db_path = self.parsed.path if self.parsed.path else "./demo.db"if self.db_path.startswith("/."): self.db_path = self.db_path[1:]else:self.type = "mysql"5 unmodified linesdef get_connection(self):if self.type == "sqlite":conn = sqlite3.connect(self.db_path, check_same_thread=False)conn.row_factory = sqlite3.Rowreturn connelse:return pymysql.connect(host=self.host,user=self.user,6 unmodified linesdef run_query(self, query):conn = self.get_connection()try:if self.type == "mysql":with conn.cursor() as cursor:cursor.execute(query)return cursor.fetchall()else:cursor = conn.cursor()cursor.execute(query)items = [dict(row) for row in cursor.fetchall()]return itemsexcept Exception as e:return [f"Error: {e}"]finally:conn.close()def get_tables(self):conn = self.get_connection()try:cursor = conn.cursor()if self.type == "sqlite":cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")tables = [row[0] for row in cursor.fetchall()]else:cursor.execute("SHOW TABLES")tables = [list(row.values())[0] for row in cursor.fetchall()]# 🔍 DEBUG: PRINT TABLES TO LOGSprint(f"\n🔍 FOUND TABLES IN DATABASE: {tables}\n")return tablesexcept Exception as e:print(f"Error fetching tables: {e}")return []1 unmodified lineconn.close()def get_table_schema(self, table_name):conn = self.get_connection()columns = []try:cursor = conn.cursor()if self.type == "sqlite":cursor.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})")else:cursor.execute(f"DESCRIBE {table_name}")rows = cursor.fetchall()for row in rows:columns.append(f"{row['Field']} ({row['Type']})")return columnsexcept Exception as e:return []finally:conn.close()def get_schema(self):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+7-27