Author SHA1 Message Date
LarsandClaude Opus 4.6 548d733048 refactor: move init_db() to db.py
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>
2026-03-19 09:49:46 +01:00
LarsandClaude Opus 4.6 6845397866 fix: Migration-Fehler - meas_id Spalte in ai_insights
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
PROBLEM:
- Backend crasht beim Start auf Prod
- Migration schlägt fehl: column 'meas_id' does not exist
- SQLite ai_insights hat Legacy-Spalte meas_id
- PostgreSQL schema hat diese Spalte nicht mehr

FIX:
- COLUMN_WHITELIST für ai_insights hinzugefügt
- Nur erlaubte Spalten werden migriert:
  id, profile_id, scope, content, created
- meas_id wird beim Import gefiltert

DATEIEN:
- backend/migrate_to_postgres.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 08:39:36 +01:00
Lars 2df70b2a6b docker-compose.yml aktualisiert
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:28:30 +01:00
LarsandClaude Opus 4.6 85f48907a4 fix: startup crash - init_db() jetzt mit Error-Handling
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
PROBLEM:
- Backend crasht beim Start auf Prod
- Login zeigt HTML statt JSON (Backend nicht erreichbar)
- Ursache: init_db() wirft Exception beim Startup

FIX:
1. startup_event() wrapped in try-except (non-fatal)
2. init_db() prüft ob ai_prompts Tabelle existiert
3. init_db() hat eigenen try-except
4. Bessere Fehlermeldungen in stdout

ERGEBNIS:
- Backend startet auch wenn init_db() fehlschlägt
- Pipeline-Prompt kann manuell angelegt werden falls nötig
- Login funktioniert wieder

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 08:26:09 +01:00
4 changed files with 69 additions and 31 deletions

No files matched your search

+45
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
+6 -26
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"))
@@ -43,31 +43,11 @@ AVATAR_COLORS = ['#1D9E75','#378ADD','#D85A30','#EF9F27','#7F77DD','#D4537E','#6
@app.on_event("startup")
async def startup_event():
"""Run migrations and initialization on startup."""
init_db()
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
with get_db() as conn:
cur = get_cursor(conn)
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")
try:
init_db()
except Exception as e:
print(f"⚠️ init_db() failed (non-fatal): {e}")
# Don't crash on startup - pipeline prompt can be created manually
# ── Helper: get profile_id from header ───────────────────────────────────────
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
+17 -2
View File
@@ -69,6 +69,12 @@ BOOLEAN_COLUMNS = {
'ai_prompts': ['active'],
}
# Column whitelist for tables that have schema differences
# Only these columns will be migrated (filters out legacy columns)
COLUMN_WHITELIST = {
'ai_insights': ['id', 'profile_id', 'scope', 'content', 'created'],
}
# ================================================================
# CONVERSION HELPERS
@@ -173,8 +179,17 @@ def migrate_table(pg_conn, table: str) -> Dict[str, int]:
# Convert rows
converted_rows = [convert_row(row, table) for row in sqlite_rows]
# Get column names
columns = list(converted_rows[0].keys())
# Get column names - filter if whitelist exists for this table
if table in COLUMN_WHITELIST:
allowed_columns = COLUMN_WHITELIST[table]
# Filter rows to only include allowed columns
converted_rows = [
{k: v for k, v in row.items() if k in allowed_columns}
for row in converted_rows
]
columns = allowed_columns
else:
columns = list(converted_rows[0].keys())
cols_str = ', '.join(columns)
placeholders = ', '.join(['%s'] * len(columns))
+1 -3
View File
@@ -1,7 +1,7 @@
services:
postgres:
image: postgres:16-alpine
container_name: mitai-db
container_name: mitai-db-prod
restart: unless-stopped
environment:
POSTGRES_DB: mitai_prod
@@ -9,8 +9,6 @@ services:
POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_in_production}
volumes:
- mitai_postgres_data:/var/lib/postgresql/data
ports:
- "127.0.0.1:5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U mitai_prod"]
interval: 10s