Paritosh Upadhyay
Million Forge Awakening: Grid Unlocked & Seeding Complete
c4a2296
"""
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")
# 1. Resolve Persistence Engine
# Use DATABASE_URL from settings (loaded from .env/Supabase) if available
DATABASE_URL = settings.database_url
# 2. Resolve Local Paths
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).")
# For Postgres, we don't need check_same_thread
engine = create_engine(DATABASE_URL)
else:
# Ensure local DB directory exists for fallback
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:
# TEST CONNECTION
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")
# Override with Local SQLite
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.")