feat: enhance database migration handling and health check endpoint
- Updated migration logic in main.py to allow skipping migrations during local development with SKIP_DB_MIGRATE environment variable. - Improved error handling for migration failures, ensuring the application does not start if migrations are incomplete. - Added a new health check endpoint (/api/health/ready) to verify database connection and essential tables, aiding in production debugging. - Enhanced run_migrations.py to support ordered execution of migration files and improved transaction handling. - Updated requirements.txt to include sqlparse for SQL statement parsing when psql is unavailable.
This commit is contained in:
1 parent
159ac8fb71
commit
1f2c8ea0f1
6 files changed
+341
-88
No files matched your search
+77
-8
@@ -4,26 +4,38 @@ Shinkan Jinkendo - Main Application Entry Point
|
||||
Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung
|
||||
"""
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
import os
|
||||
import sys
|
||||
|
||||
from slowapi import _rate_limit_exceeded_handler
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
|
||||
from version import APP_VERSION, BUILD_DATE, DB_SCHEMA_VERSION, MODULE_VERSIONS
|
||||
|
||||
# Run database migrations on startup
|
||||
try:
|
||||
import run_migrations
|
||||
run_migrations.main()
|
||||
print("✓ Database migrations completed")
|
||||
except Exception as e:
|
||||
print(f"⚠ Warning: Migration error: {e}")
|
||||
print(" Continuing startup - migrations may need manual intervention")
|
||||
# Run database migrations before API start — halbes Schema ist schlimmer als kein Start
|
||||
# Lokal ohne DB / nur Tests: SKIP_DB_MIGRATE=1
|
||||
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() in ("1", "true", "yes"):
|
||||
print("⚠ SKIP_DB_MIGRATE=1 — Migrationen wurden übersprungen (nur für Entwicklung ohne DB)")
|
||||
else:
|
||||
try:
|
||||
import run_migrations
|
||||
|
||||
rc = run_migrations.main()
|
||||
if rc != 0:
|
||||
print(f"✗ Datenbank-Migration fehlgeschlagen (Exit-Code {rc}). Start abgebrochen.")
|
||||
sys.exit(1)
|
||||
print("✓ Database migrations completed")
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"✗ Migration-Laufzeitfehler: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
from routers.auth import limiter as auth_rate_limiter
|
||||
|
||||
@@ -71,6 +83,63 @@ def health_check():
|
||||
"""Health check endpoint"""
|
||||
return {"status": "healthy", "version": APP_VERSION}
|
||||
|
||||
|
||||
@app.get("/api/health/ready")
|
||||
def health_ready():
|
||||
"""
|
||||
Verbindung + Kern-Tabellen prüfen (ohne Login).
|
||||
Nutzen bei Prod-Debugging: wenn schema_complete=false, Migrationen nicht vollständig.
|
||||
"""
|
||||
from db import get_db, get_cursor
|
||||
|
||||
REQUIRED = (
|
||||
"schema_migrations",
|
||||
"skills",
|
||||
"skill_main_categories",
|
||||
"skill_categories",
|
||||
"maturity_models",
|
||||
"sessions",
|
||||
)
|
||||
tables: dict = {}
|
||||
err: Optional[str] = None
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT 1")
|
||||
for tbl in REQUIRED:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM information_schema.tables
|
||||
WHERE table_schema = 'public' AND table_name = %s
|
||||
)
|
||||
""",
|
||||
(tbl,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
tables[tbl] = bool(next(iter(row.values()))) if row else False
|
||||
migration_count = 0
|
||||
if tables.get("schema_migrations"):
|
||||
cur.execute("SELECT COUNT(*)::int FROM schema_migrations")
|
||||
mig_row = cur.fetchone()
|
||||
migration_count = (
|
||||
int(list(mig_row.values())[0]) if mig_row is not None else 0
|
||||
)
|
||||
except Exception as e:
|
||||
err = str(e)
|
||||
migration_count = 0
|
||||
|
||||
complete = bool(err is None and all(tables.get(t) for t in REQUIRED))
|
||||
return {
|
||||
"status": "ready" if complete else "degraded",
|
||||
"database": err is None,
|
||||
"detail": err,
|
||||
"schema_complete": complete,
|
||||
"tables": tables,
|
||||
"schema_migrations_count": migration_count,
|
||||
}
|
||||
|
||||
|
||||
# Root Endpoint
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
|
||||
Reference in new issue
Block a user