From d7eb86b0c06bbd6fdbcc929ad6ff97f1dc2852eb Mon Sep 17 00:00:00 2001 From: Yves Gugger Date: Wed, 17 Dec 2025 12:00:23 +0100 Subject: [PATCH] Fix: Robust DB connection for zone sync - reads DATABASE_URL directly from .env --- backend/scripts/sync_all_zones.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/backend/scripts/sync_all_zones.py b/backend/scripts/sync_all_zones.py index 2a2de4d..5070188 100644 --- a/backend/scripts/sync_all_zones.py +++ b/backend/scripts/sync_all_zones.py @@ -86,13 +86,31 @@ class ZoneSyncResult: async def get_db_session(): - """Create async database session for zone sync script""" - # Direct path to DB (script runs from backend/ directory) - db_path = Path("/home/user/pounce/backend/domainwatch.db") - if not db_path.exists(): - db_path = Path("domainwatch.db") + """Create async database session - ROBUST VERSION for standalone script""" + # Read DATABASE_URL directly from .env (avoids import issues when running standalone) + env_file = Path("/home/user/pounce/backend/.env") + if not env_file.exists(): + env_file = Path(__file__).parent.parent / ".env" - db_url = f"sqlite+aiosqlite:///{db_path}" + db_url = None + if env_file.exists(): + for line in env_file.read_text().splitlines(): + if line.startswith("DATABASE_URL="): + db_url = line.split("=", 1)[1].strip().strip('"').strip("'") + break + + # Default to SQLite if not found + if not db_url: + db_url = "sqlite:///./domainwatch.db" + logger.warning(f"DATABASE_URL not found in .env, using default: {db_url}") + + # Convert to async driver + if "sqlite://" in db_url and "aiosqlite" not in db_url: + db_url = db_url.replace("sqlite://", "sqlite+aiosqlite://") + elif "postgresql://" in db_url and "asyncpg" not in db_url: + db_url = db_url.replace("postgresql://", "postgresql+asyncpg://") + + logger.info(f"Database URL: {db_url[:50]}...") engine = create_async_engine(db_url, echo=False) async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)