Spaces:
Running
Running
| """ | |
| Database functionality for the agent monitoring system. | |
| This package provides database access and utilities for agent monitoring. | |
| """ | |
| import os | |
| from sqlalchemy import create_engine | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from sqlalchemy.orm import sessionmaker, scoped_session | |
| # Import DB_URI from central config (handles HF Spaces vs local dev) | |
| from utils.config import DB_URI | |
| DATABASE_URL = DB_URI | |
| # Create engine | |
| engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) | |
| # Create session factory | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| # Create a scoped session for thread safety | |
| Session = scoped_session(SessionLocal) | |
| # Base class for models | |
| Base = declarative_base() | |
| # Function to get database session | |
| def get_db(): | |
| db = Session() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |
| # Import models and utility functions | |
| from backend.database.models import KnowledgeGraph, Entity, Relation, Base | |
| from backend.database.utils import ( | |
| save_knowledge_graph, | |
| update_knowledge_graph_status, | |
| get_knowledge_graph, | |
| get_all_knowledge_graphs, | |
| delete_knowledge_graph | |
| ) | |
| # Function to initialize database | |
| def init_db(): | |
| """Initialize the database by creating all tables.""" | |
| Base.metadata.create_all(bind=engine) | |
| __all__ = [ | |
| 'get_db', | |
| 'models', | |
| 'init_db', | |
| 'save_knowledge_graph', | |
| 'update_knowledge_graph_status', | |
| 'get_knowledge_graph', | |
| 'get_all_knowledge_graphs', | |
| 'delete_knowledge_graph', | |
| 'KnowledgeGraph', | |
| 'Entity', | |
| 'Relation' | |
| ] | |