diff --git a/Dockers/puppeteer-api/app/database.py b/Dockers/puppeteer-api/app/database.py index b097cae..6d1d7dc 100644 --- a/Dockers/puppeteer-api/app/database.py +++ b/Dockers/puppeteer-api/app/database.py @@ -76,6 +76,25 @@ class DatabaseManager: self.db_path = db_path + def _wait_for_postgres(self, max_retries=30, retry_delay=2): + """Wait for PostgreSQL to be ready""" + print(f"Waiting for PostgreSQL at {POSTGRES_HOST}:{POSTGRES_PORT}...") + + for attempt in range(max_retries): + try: + conn = self.psycopg2.connect(**self.connection_params) + conn.close() + print(f"PostgreSQL is ready after {attempt + 1} attempts") + return True + except Exception as e: + if attempt < max_retries - 1: + print(f"PostgreSQL not ready (attempt {attempt + 1}/{max_retries}): {e}") + time.sleep(retry_delay) + else: + print(f"PostgreSQL connection failed after {max_retries} attempts: {e}") + return False + return False + def get_connection(self): """Get database connection based on configured database type""" if self.db_type == "postgresql": @@ -93,6 +112,14 @@ class DatabaseManager: def _init_postgres_db(self): """Initialize PostgreSQL database""" try: + # Wait for PostgreSQL to be ready + if not self._wait_for_postgres(): + print("PostgreSQL connection failed, falling back to SQLite") + self.db_type = "sqlite" + self._init_sqlite_path() + self._init_sqlite_db() + return + conn = self.get_connection() cursor = conn.cursor()