File: //opt/kw-schueler.bak.21032025/apply_sharing_and_visibility.py
#!/usr/bin/env python3
import mysql.connector
import os
from dotenv import load_dotenv
def execute_sql_commands(cursor, filename):
"""Führt SQL-Befehle einzeln aus."""
with open(filename, 'r') as f:
sql_content = f.read()
# Teile den SQL-Content in einzelne Befehle
commands = []
current_command = ''
for line in sql_content.split('\n'):
if line.strip().startswith('--'): # Überspringe Kommentare
continue
if 'DELIMITER' in line: # Überspringe DELIMITER-Zeilen
if current_command:
commands.append(current_command)
current_command = ''
continue
current_command += line + '\n'
if line.strip().endswith(';'):
if current_command.strip():
commands.append(current_command)
current_command = ''
# Führe jeden Befehl einzeln aus
for command in commands:
command = command.strip()
if not command:
continue
try:
cursor.execute(command)
print(f"Befehl erfolgreich ausgeführt: {command[:100]}...")
except mysql.connector.Error as err:
print(f"Fehler beim Ausführen des Befehls: {err}")
print(f"Befehl: {command[:100]}...")
if "already exists" not in str(err): # Ignoriere "already exists" Fehler
raise
def main():
# Lade Umgebungsvariablen
load_dotenv()
# Verbindung zur Datenbank herstellen
try:
conn = mysql.connector.connect(
host=os.getenv('DB_HOST'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
database=os.getenv('DB_NAME')
)
cursor = conn.cursor()
# Führe das SQL-Skript aus
print("Führe SQL-Skript aus...")
execute_sql_commands(cursor, 'add_sharing_and_visibility.sql')
# Commit der Änderungen
conn.commit()
print("SQL-Skript erfolgreich ausgeführt!")
except mysql.connector.Error as err:
print(f"Fehler bei der Datenbankverbindung: {err}")
finally:
if 'conn' in locals() and conn.is_connected():
cursor.close()
conn.close()
if __name__ == "__main__":
main()