From 7860aa3579e6066772b048fc702186a6fbedc9f5 Mon Sep 17 00:00:00 2001 From: Bram Date: Wed, 16 Jul 2025 10:32:01 +0200 Subject: [PATCH] gotta love ai --- Dockers/puppeteer-api/app/database.py | 41 ++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/Dockers/puppeteer-api/app/database.py b/Dockers/puppeteer-api/app/database.py index 6d1d7dc..9070566 100644 --- a/Dockers/puppeteer-api/app/database.py +++ b/Dockers/puppeteer-api/app/database.py @@ -82,7 +82,10 @@ class DatabaseManager: for attempt in range(max_retries): try: - conn = self.psycopg2.connect(**self.connection_params) + # First try to connect to the default 'postgres' database + default_params = self.connection_params.copy() + default_params['database'] = 'postgres' + conn = self.psycopg2.connect(**default_params) conn.close() print(f"PostgreSQL is ready after {attempt + 1} attempts") return True @@ -95,6 +98,34 @@ class DatabaseManager: return False return False + def _create_database_if_not_exists(self): + """Create the target database if it doesn't exist""" + try: + # Connect to the default 'postgres' database + default_params = self.connection_params.copy() + default_params['database'] = 'postgres' + conn = self.psycopg2.connect(**default_params) + conn.autocommit = True # Required for CREATE DATABASE + cursor = conn.cursor() + + # Check if the target database exists + cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", (POSTGRES_DB,)) + exists = cursor.fetchone() + + if not exists: + print(f"Creating database '{POSTGRES_DB}'...") + cursor.execute(f"CREATE DATABASE {POSTGRES_DB}") + print(f"Database '{POSTGRES_DB}' created successfully") + else: + print(f"Database '{POSTGRES_DB}' already exists") + + cursor.close() + conn.close() + return True + except Exception as e: + print(f"Error creating database: {e}") + return False + def get_connection(self): """Get database connection based on configured database type""" if self.db_type == "postgresql": @@ -120,6 +151,14 @@ class DatabaseManager: self._init_sqlite_db() return + # Create the target database if it doesn't exist + if not self._create_database_if_not_exists(): + print("Failed to create or check database, falling back to SQLite") + self.db_type = "sqlite" + self._init_sqlite_path() + self._init_sqlite_db() + return + conn = self.get_connection() cursor = conn.cursor()