feat: Added database utility functions

This commit is contained in:
Lino Mallevaey
2025-08-19 12:17:11 +02:00
parent 660dcbe888
commit 756af47782
2 changed files with 112 additions and 3 deletions

49
app/db/utils.py Normal file
View File

@@ -0,0 +1,49 @@
from app.db.engine import engine
from app.db.session import SessionLocal
from app.db.models import *
from app.core.config import settings
def init_db():
try:
if settings.DEBUG:
print("Creating database tables...")
Base.metadata.create_all(bind=engine)
if settings.DEBUG:
print("Database tables created.")
except Exception as e:
print(f"Error creating database tables: {e}")
raise
finally:
if settings.DEBUG:
print("Tables :", Base.metadata.tables.keys())
def clear_db():
try:
if settings.DEBUG:
print("Deleting database tables...")
Base.metadata.drop_all(bind=engine)
if settings.DEBUG:
print("Database tables deleted.")
except Exception as e:
print(f"Error deleting database tables: {e}")
raise
def reset_db():
session = SessionLocal()
try:
if settings.DEBUG:
print("Deleting database rows...")
for table in reversed(Base.metadata.sorted_tables):
session.execute(table.delete())
session.commit()
if settings.DEBUG:
print("Database rows deleted.")
except Exception as e:
print(f"Error deleting database rows: {e}")
raise
finally:
session.close()