| """ |
| Project Jarvis — Database Configuration |
| Setup SQLAlchemy for Sovereign Persistence (Supabase / Postgres / SQLite) |
| """ |
| import os |
| import logging |
| from sqlalchemy import create_engine |
| from sqlalchemy.orm import sessionmaker, declarative_base |
| from config import settings |
|
|
| logger = logging.getLogger("friday.database") |
|
|
| |
| |
| DATABASE_URL = settings.database_url |
|
|
| |
| DB_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "data") |
| DB_PATH = os.path.join(DB_DIR, "friday.db") |
|
|
| if DATABASE_URL: |
| logger.info("Persistence: Engaging Cloud Sovereign Core (PostgreSQL).") |
| |
| engine = create_engine(DATABASE_URL) |
| else: |
| |
| os.makedirs(DB_DIR, exist_ok=True) |
| DATABASE_URL = f"sqlite:///{DB_PATH}" |
| logger.info(f"Persistence: Local Mode Active (SQLite). Data stored at {DB_PATH}") |
| engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) |
|
|
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) |
|
|
| Base = declarative_base() |
|
|
| def get_db(): |
| db = SessionLocal() |
| try: |
| yield db |
| finally: |
| db.close() |
|
|
| def init_db(): |
| global engine, SessionLocal |
| try: |
| |
| from sqlalchemy import text |
| with engine.connect() as conn: |
| conn.execute(text("SELECT 1")) |
| |
| from app.models import entities |
| Base.metadata.create_all(bind=engine) |
| logger.info("Database Schema Initialized successfully on Cloud Grid.") |
| except Exception as e: |
| logger.warning(f"Persistence: Cloud grid unreachable or DNS stall detected. Error: {e}") |
| logger.info(f"Persistence: Initiating SEAMLESS LOCAL FALLBACK") |
| |
| |
| local_url = f"sqlite:///{DB_PATH}" |
| engine = create_engine(local_url, connect_args={"check_same_thread": False}) |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) |
| |
| from app.models import entities |
| Base.metadata.create_all(bind=engine) |
| logger.info("Database Schema Initialized successfully on LOCAL SOVEREIGN CORE.") |
|
|