refactor: move init_db() to db.py
All checks were successful
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s

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 <noreply@anthropic.com>
This commit is contained in:
Lars 2026-03-19 09:49:46 +01:00
parent 6845397866
commit 548d733048
2 changed files with 46 additions and 41 deletions

View File

@ -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

View File

@ -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."""