30 lines
1.1 KiB
Python
30 lines
1.1 KiB
Python
|
from sqlalchemy import inspect, Integer, String
|
||
|
|
||
|
def check_and_create_tables(db):
|
||
|
inspector = inspect(db.engine)
|
||
|
|
||
|
# Überprüfen, ob die Tabelle 'user' existiert
|
||
|
if not inspector.has_table('user'):
|
||
|
print("Tabelle 'user' existiert nicht, sie wird erstellt.")
|
||
|
db.create_all()
|
||
|
else:
|
||
|
print("Tabelle 'user' existiert.")
|
||
|
# Überprüfen der Spalten
|
||
|
columns = inspector.get_columns('user')
|
||
|
column_names = [col['name'] for col in columns]
|
||
|
|
||
|
# Benötigte Spalten
|
||
|
required_columns = {
|
||
|
'id': Integer,
|
||
|
'username': String,
|
||
|
'email': String
|
||
|
}
|
||
|
|
||
|
for col_name, col_type in required_columns.items():
|
||
|
if col_name not in column_names:
|
||
|
print(f"Spalte '{col_name}' fehlt, sie wird hinzugefügt.")
|
||
|
with db.engine.connect() as conn:
|
||
|
if col_type == Integer:
|
||
|
conn.execute(f'ALTER TABLE user ADD COLUMN {col_name} INTEGER')
|
||
|
elif col_type == String:
|
||
|
conn.execute(f'ALTER TABLE user ADD COLUMN {col_name} STRING')
|