#!/usr/bin/python3 # DB-Dump für motorradig2027. # Voraussetzung: mysqldump muss installiert sein (apt install mysql-client). # Die Zugangsdaten werden aus ../motorradig/.credentials gelesen (KEY=VALUE). # # Beispiele: # python3 tools/dump_motorradig.py # python3 tools/dump_motorradig.py --output /tmp/opencode from __future__ import annotations import argparse import datetime import os import subprocess import sys CRED_FILE = os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', 'motorradig', '.credentials' ) def load_credentials(path: str) -> dict: creds = {} if not os.path.isfile(path): print(f"Fehler: Credentials-Datei nicht gefunden: {path}", file=sys.stderr) sys.exit(1) with open(path, 'r', encoding='utf-8') as fh: for line in fh: line = line.strip() if not line or line.startswith('#') or '=' not in line: continue key, value = line.split('=', 1) creds[key.strip()] = value.strip() return creds def dump_database(output_dir: str = '.', creds: dict | None = None) -> str: """Schreibt einen DB-Dump nach output_dir und gibt den Pfad zurück.""" if creds is None: creds = load_credentials(CRED_FILE) db_host = creds.get('DB_HOST', creds.get('FTP_URL', '')) db_user = creds.get('DB_USERNAME', '') db_password = creds.get('DB_PASSWORD', '') db_name = creds.get('DB_NAME', db_user) missing = [] if not db_host: missing.append('DB_HOST (oder FTP_URL)') if not db_user: missing.append('DB_USERNAME') if not db_password: missing.append('DB_PASSWORD') if not db_name: missing.append('DB_NAME (oder DB_USERNAME)') if missing: raise RuntimeError('Fehlende Credentials: ' + ', '.join(missing)) os.makedirs(output_dir, exist_ok=True) now = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S') path = os.path.join(output_dir, 'motorradig_' + now + '.sql') print(f'Dumping {path} (Host: {db_host}, DB: {db_name})') cmd = [ 'mysqldump', '--no-tablespaces', '--column-statistics=0', '--single-transaction', '--quick', '--user=' + db_user, '--password=' + db_password, '--host=' + db_host, db_name, ] with open(path, 'w', encoding='utf-8') as out: result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE) if result.returncode != 0: # Unvollständigen Dump nicht liegen lassen. try: os.unlink(path) except OSError: pass raise RuntimeError(result.stderr.decode('utf-8', 'replace').strip()) return path def main() -> int: parser = argparse.ArgumentParser(description='Datenbank-Dump von motorradig2027 erzeugen.') parser.add_argument('--output', default='.', help='Zielverzeichnis für den Dump (Standard: aktuelles Verzeichnis).') args = parser.parse_args() try: path = dump_database(args.output) except RuntimeError as exc: print('Fehler: ' + str(exc), file=sys.stderr) return 1 print('Fertig: ' + path) return 0 if __name__ == '__main__': sys.exit(main())