|
|
@@ -44,23 +44,43 @@ app.mount("/static", StaticFiles(directory="backend/app/static"), name="static")
|
|
|
|
|
|
def init_db_if_not_exists():
|
|
|
"""Check if database exists, create if not."""
|
|
|
- try:
|
|
|
- logger.info(f"Connecting to MySQL server at {settings.MYSQL_SERVER} to check database...")
|
|
|
- conn = pymysql.connect(
|
|
|
- host=settings.MYSQL_SERVER,
|
|
|
- user=settings.MYSQL_USER,
|
|
|
- password=settings.MYSQL_PASSWORD,
|
|
|
- port=int(settings.MYSQL_PORT),
|
|
|
- charset='utf8mb4',
|
|
|
- cursorclass=pymysql.cursors.DictCursor
|
|
|
- )
|
|
|
- with conn.cursor() as cursor:
|
|
|
- logger.info(f"Checking database {settings.MYSQL_DB}...")
|
|
|
- cursor.execute(f"CREATE DATABASE IF NOT EXISTS {settings.MYSQL_DB} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")
|
|
|
- logger.info("Database checked/created.")
|
|
|
- conn.close()
|
|
|
- except Exception as e:
|
|
|
- logger.error(f"Database initialization failed: {e}")
|
|
|
+ max_retries = 30
|
|
|
+ retry_interval = 2 # seconds
|
|
|
+
|
|
|
+ for attempt in range(max_retries):
|
|
|
+ try:
|
|
|
+ logger.info(f"Connecting to MySQL server at {settings.MYSQL_SERVER} to check database (Attempt {attempt + 1}/{max_retries})...")
|
|
|
+ conn = pymysql.connect(
|
|
|
+ host=settings.MYSQL_SERVER,
|
|
|
+ user=settings.MYSQL_USER,
|
|
|
+ password=settings.MYSQL_PASSWORD,
|
|
|
+ port=int(settings.MYSQL_PORT),
|
|
|
+ charset='utf8mb4',
|
|
|
+ cursorclass=pymysql.cursors.DictCursor
|
|
|
+ )
|
|
|
+ with conn.cursor() as cursor:
|
|
|
+ logger.info(f"Checking database {settings.MYSQL_DB}...")
|
|
|
+ cursor.execute(f"CREATE DATABASE IF NOT EXISTS {settings.MYSQL_DB} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")
|
|
|
+ logger.info("Database checked/created.")
|
|
|
+ conn.close()
|
|
|
+ return # Success
|
|
|
+ except pymysql.err.OperationalError as e:
|
|
|
+ if e.args[0] == 2003: # Connection refused
|
|
|
+ logger.warning(f"Database not ready yet, retrying in {retry_interval}s...")
|
|
|
+ import time
|
|
|
+ time.sleep(retry_interval)
|
|
|
+ else:
|
|
|
+ logger.error(f"Database initialization failed: {e}")
|
|
|
+ # Don't raise immediately, maybe transient? But usually logic error.
|
|
|
+ # Let's retry anyway to be safe, or break if critical.
|
|
|
+ time.sleep(retry_interval)
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"Database initialization failed: {e}")
|
|
|
+ import time
|
|
|
+ time.sleep(retry_interval)
|
|
|
+
|
|
|
+ logger.error("Could not connect to database after multiple attempts.")
|
|
|
+ # raise Exception("Database connection failed") # Optional: crash app
|
|
|
|
|
|
# Startup Event
|
|
|
@app.on_event("startup")
|