create schema if not existing

This commit is contained in:
2026-08-04 23:03:32 +02:00
parent e5b9fb8a67
commit 236f415efe
3 changed files with 30 additions and 0 deletions
+21
View File
@@ -1,5 +1,6 @@
"""MariaDB-Anbindung: Delta-Sync-Strategie (Upsert für Änderungen, gezieltes Löschen für Removals)."""
import logging
import os
import uuid
from contextlib import contextmanager
@@ -10,6 +11,8 @@ from config import Config
logger = logging.getLogger(__name__)
SCHEMA_PATH = os.path.join(os.path.dirname(__file__), "..", "sql", "schema.sql")
@contextmanager
def get_connection():
@@ -24,6 +27,24 @@ def get_connection():
conn.close()
def ensure_schema():
"""Legt alle Tabellen an, falls sie noch nicht existieren (idempotent)."""
schema_file = os.path.normpath(SCHEMA_PATH)
if not os.path.exists(schema_file):
logger.warning("Schema-Datei nicht gefunden: %s — überspringe Init", schema_file)
return
with open(schema_file, "r", encoding="utf-8") as f:
sql = f.read()
with get_connection() as conn:
with conn.cursor() as cur:
for statement in sql.split(";"):
statement = statement.strip()
if statement:
cur.execute(statement)
conn.commit()
logger.info("Datenbank-Schema geprüft/initialisiert")
def get_sync_token(conn, account: str) -> str | None:
with conn.cursor() as cur:
cur.execute("SELECT sync_token FROM sync_state WHERE account = %s", (account,))
+8
View File
@@ -16,6 +16,8 @@ import sys
import time
from datetime import datetime, timedelta
import db
logging.basicConfig(
level=os.environ.get("LOG_LEVEL", "INFO"),
format="%(asctime)s [%(levelname)s] %(message)s",
@@ -90,6 +92,12 @@ def main():
else:
logger.info("Mailer: deaktiviert (MAILER_ENABLED=false)")
logger.info("Pruefe/initialisiere Datenbank-Schema...")
try:
db.ensure_schema()
except Exception:
logger.exception("Schema-Init fehlgeschlagen — Sync wird trotzdem gestartet")
logger.info("Fuehre initialen Sync aus...")
run_sync()