Add datetime import and buffer for alembic log

This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-04-03 15:48:38 -03:00
commit 7e091a1633

View file

@ -1,3 +1,4 @@
from datetime import datetime
import time
from pathlib import Path
from typing import TYPE_CHECKING
@ -124,10 +125,16 @@ class DatabaseService(Service):
# if not self.script_location.exists(): # this is not the correct way to check if alembic has been initialized
# We need to check if the alembic_version table exists
# if not, we need to initialize alembic
alembic_cfg = Config()
# stdout should be something like sys.stdout
# which is a buffer
# I don't want to output anything
# subprocess.DEVNULL is an int
buffer = open(self.script_location / "alembic.log", "w")
alembic_cfg = Config(stdout=buffer)
# alembic_cfg.attributes["connection"] = session
alembic_cfg.set_main_option("script_location", str(self.script_location))
alembic_cfg.set_main_option("sqlalchemy.url", self.database_url)
should_initialize_alembic = False
with Session(self.engine) as session:
# If the table does not exist it throws an error
@ -150,6 +157,7 @@ class DatabaseService(Service):
logger.info(f"Running DB migrations in {self.script_location}")
try:
buffer.write(f"{datetime.now().isoformat()}: Checking migrations\n")
command.check(alembic_cfg)
except Exception as exc:
if isinstance(exc, (util.exc.CommandError, util.exc.AutogenerateDiffsDetected)):
@ -157,6 +165,7 @@ class DatabaseService(Service):
time.sleep(3)
try:
buffer.write(f"{datetime.now().isoformat()}: Checking migrations\n")
command.check(alembic_cfg)
except util.exc.AutogenerateDiffsDetected as exc:
logger.error(f"AutogenerateDiffsDetected: {exc}")