HEX
Server: LiteSpeed
System: Linux houston.panomity.com 6.8.0-100-generic #100-Ubuntu SMP PREEMPT_DYNAMIC Tue Jan 13 16:40:06 UTC 2026 x86_64
User: nudepix (1011)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: //opt/af/scripts/export_db_schema.py
#!/usr/bin/env python
"""
Hilfsprogramm zum Exportieren des MySQL-Datenbankschemas.

Verbindet sich mit der konfigurierten MySQL-Datenbank und speichert
die `CREATE DATABASE` und `CREATE TABLE` Anweisungen in einer SQL-Datei.
Liest die Datenbankkonfiguration aus der .env-Datei.
"""

import sys
import os
import logging
from datetime import datetime

# Füge das Projekt-Stammverzeichnis zum Python-Pfad hinzu
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, project_root)

# Lade Umgebungsvariablen
from dotenv import load_dotenv
dotenv_path = os.path.join(project_root, '.env')
load_dotenv(dotenv_path=dotenv_path)

from src.database import get_mysql_connection

# Logging konfigurieren
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Standard-Ausgabedatei (kann über Kommandozeile überschrieben werden)
DEFAULT_OUTPUT_DIR = os.path.join(project_root, "data")
DEFAULT_OUTPUT_FILE = os.path.join(DEFAULT_OUTPUT_DIR, f"db_schema_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql")

def export_schema(output_file):
    """
    Exportiert das Datenbankschema in die angegebene Datei.

    Args:
        output_file (str): Der Pfad zur Ausgabedatei.
    """
    conn = None
    cursor = None
    db_name = os.getenv("MYSQL_DATABASE")

    if not db_name:
        logging.error("MYSQL_DATABASE ist nicht in der .env-Datei gesetzt.")
        return False

    try:
        conn = get_mysql_connection()
        if not conn or not conn.is_connected():
            logging.error("Konnte keine Verbindung zur MySQL-Datenbank herstellen.")
            return False

        cursor = conn.cursor()
        logging.info(f"Verbunden mit Datenbank '{db_name}'. Exportiere Schema nach '{output_file}'...")

        # Stelle sicher, dass das Ausgabeverzeichnis existiert
        output_dir = os.path.dirname(output_file)
        os.makedirs(output_dir, exist_ok=True)

        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(f"-- Schema Export für Datenbank '{db_name}' am {datetime.now()}\n")
            f.write(f"-- Generiert von scripts/export_db_schema.py\n\n")

            # 1. CREATE DATABASE Anweisung holen
            logging.info("Exportiere CREATE DATABASE Anweisung...")
            cursor.execute(f"SHOW CREATE DATABASE `{db_name}`")
            result = cursor.fetchone()
            if result:
                create_db_statement = result[1]
                f.write(f"{create_db_statement};\n\n")
            else:
                logging.warning("Konnte SHOW CREATE DATABASE nicht abrufen.")

            f.write(f"USE `{db_name}`;\n\n")

            # 2. Tabellennamen holen
            logging.info("Suche nach Tabellen...")
            cursor.execute("SHOW TABLES")
            tables = [row[0] for row in cursor.fetchall()]
            logging.info(f"{len(tables)} Tabellen gefunden: {tables}")

            # 3. CREATE TABLE Anweisungen für jede Tabelle holen
            for table_name in tables:
                logging.info(f"Exportiere Schema für Tabelle '{table_name}'...")
                try:
                    cursor.execute(f"SHOW CREATE TABLE `{table_name}`")
                    result = cursor.fetchone()
                    if result:
                        create_table_statement = result[1]
                        f.write(f"-- Struktur für Tabelle '{table_name}'\n")
                        f.write(f"{create_table_statement};\n\n")
                    else:
                        logging.warning(f"Konnte SHOW CREATE TABLE für '{table_name}' nicht abrufen.")
                except Exception as table_err:
                    logging.error(f"Fehler beim Exportieren der Tabelle '{table_name}': {table_err}")

            logging.info(f"Schema erfolgreich nach '{output_file}' exportiert.")
            return True

    except Exception as e:
        logging.error(f"Fehler beim Exportieren des Schemas: {e}", exc_info=True)
        return False
    finally:
        if cursor:
            cursor.close()
        if conn and conn.is_connected():
            conn.close()
            logging.info("MySQL-Verbindung geschlossen.")

if __name__ == "__main__":
    output_arg = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_OUTPUT_FILE
    if not export_schema(output_arg):
        sys.exit(1)