From 548d7330489b8bc40530008e2da804916a2c93f3 Mon Sep 17 00:00:00 2001 From: Lars Date: Thu, 19 Mar 2026 09:49:46 +0100 Subject: [PATCH] refactor: move init_db() to db.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1.1 - Database-Logik konsolidieren ÄNDERUNGEN: - init_db() von main.py nach db.py verschoben - main.py importiert init_db von db - startup_event() ruft db.init_db() auf - Keine funktionalen Änderungen DATEIEN: - backend/db.py: +60 Zeilen (init_db Funktion) - backend/main.py: -48 Zeilen (init_db entfernt, import hinzugefügt) Co-Authored-By: Claude Opus 4.6 --- backend/db.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ backend/main.py | 42 +----------------------------------------- 2 files changed, 46 insertions(+), 41 deletions(-) diff --git a/backend/db.py b/backend/db.py index d6dff6a..9699bae 100644 --- a/backend/db.py +++ b/backend/db.py @@ -148,3 +148,48 @@ def execute_write(conn, query: str, params: tuple = ()) -> None: """ with get_cursor(conn) as cur: cur.execute(query, params) + + +def init_db(): + """ + Initialize database with required data. + + Ensures critical data exists (e.g., pipeline master prompt). + Safe to call multiple times - checks before inserting. + Called automatically on app startup. + """ + try: + with get_db() as conn: + cur = get_cursor(conn) + + # Check if table exists first + cur.execute(""" + SELECT EXISTS ( + SELECT FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name = 'ai_prompts' + ) as table_exists + """) + if not cur.fetchone()['table_exists']: + print("⚠️ ai_prompts table doesn't exist yet - skipping pipeline prompt creation") + return + + # Ensure "pipeline" master prompt exists + cur.execute("SELECT COUNT(*) as count FROM ai_prompts WHERE slug='pipeline'") + if cur.fetchone()['count'] == 0: + cur.execute(""" + INSERT INTO ai_prompts (slug, name, description, template, active, sort_order) + VALUES ( + 'pipeline', + 'Mehrstufige Gesamtanalyse', + 'Master-Schalter für die gesamte Pipeline. Deaktiviere diese Analyse, um die Pipeline komplett zu verstecken.', + 'PIPELINE_MASTER', + true, + -10 + ) + """) + conn.commit() + print("✓ Pipeline master prompt created") + except Exception as e: + print(f"⚠️ Could not create pipeline prompt: {e}") + # Don't fail startup - prompt can be created manually diff --git a/backend/main.py b/backend/main.py index ec21ad1..49f85b1 100644 --- a/backend/main.py +++ b/backend/main.py @@ -15,7 +15,7 @@ from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded from starlette.requests import Request -from db import get_db, get_cursor, r2d +from db import get_db, get_cursor, r2d, init_db DATA_DIR = Path(os.getenv("DATA_DIR", "./data")) PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos")) @@ -49,46 +49,6 @@ async def startup_event(): print(f"⚠️ init_db() failed (non-fatal): {e}") # Don't crash on startup - pipeline prompt can be created manually -def init_db(): - """Initialize database - Schema is loaded by startup.sh""" - # Schema loading and migration handled by startup.sh - # This function kept for backwards compatibility - - # Ensure "pipeline" master prompt exists - try: - with get_db() as conn: - cur = get_cursor(conn) - # Check if table exists first - cur.execute(""" - SELECT EXISTS ( - SELECT FROM information_schema.tables - WHERE table_schema = 'public' - AND table_name = 'ai_prompts' - ) as table_exists - """) - if not cur.fetchone()['table_exists']: - print("⚠️ ai_prompts table doesn't exist yet - skipping pipeline prompt creation") - return - - cur.execute("SELECT COUNT(*) as count FROM ai_prompts WHERE slug='pipeline'") - if cur.fetchone()['count'] == 0: - cur.execute(""" - INSERT INTO ai_prompts (slug, name, description, template, active, sort_order) - VALUES ( - 'pipeline', - 'Mehrstufige Gesamtanalyse', - 'Master-Schalter für die gesamte Pipeline. Deaktiviere diese Analyse, um die Pipeline komplett zu verstecken.', - 'PIPELINE_MASTER', - true, - -10 - ) - """) - conn.commit() - print("✓ Pipeline master prompt created") - except Exception as e: - print(f"⚠️ Could not create pipeline prompt: {e}") - # Don't fail startup - prompt can be created manually - # ── Helper: get profile_id from header ─────────────────────────────────────── def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str: """Get profile_id - from header for legacy endpoints."""