This commit is contained in:
@@ -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()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user