sql-agent-backend / database.py
Huzaifa1435's picture
Deploy AI SQL Agent Backend
345a446
Raw History Blame Contribute Delete
1.96 kB
import sqlite3
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_DB_PATH = os.path.join(BASE_DIR, "database", "company.db")
# Holds the currently active database path
_current_db_path = DEFAULT_DB_PATH
def set_db_path(path: str):
global _current_db_path
_current_db_path = path
def get_db_path() -> str:
return _current_db_path
def get_connection():
return sqlite3.connect(_current_db_path)
def execute_query(query: str, params=None):
conn = get_connection()
cursor = conn.cursor()
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
conn.commit()
conn.close()
def fetch_query(query: str, params=None):
conn = get_connection()
cursor = conn.cursor()
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
# Return list of dicts
columns = [desc[0] for desc in cursor.description]
rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
conn.close()
return rows
def get_schema_info(db_path: str) -> str:
"""Extract full schema string from a SQLite database."""
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [row[0] for row in cursor.fetchall()]
schema_parts = []
for table in tables:
cursor.execute(f"PRAGMA table_info({table})")
cols = cursor.fetchall()
col_defs = []
for col in cols:
col_name = col[1]
col_type = col[2]
pk = " PRIMARY KEY" if col[5] else ""
col_defs.append(f" {col_name} {col_type}{pk}")
schema_parts.append(f"{table}(\n" + ",\n".join(col_defs) + "\n)")
conn.close()
return "\n\n".join(schema_parts)
except Exception as e:
return f"Error reading schema: {e}"