Open-Assistant
Open-Assistant copied to clipboard
Update main.py
One way to make this code more efficient would be to only run the alembic upgrade on startup if the database is not already up to date. To do this, you could check the current alembic version before running the upgrade, and only run the upgrade if the current version is not the latest version.
Here's an example of how you could modify the alembic_upgrade function to do this: @app.on_event("startup") def alembic_upgrade(): logger.info("Checking alembic version on startup") alembic_ini_path = os.path.join(os.path.dirname(file), "alembic.ini") alembic_cfg = config.Config(alembic_ini_path) alembic_cfg.set_main_option("sqlalchemy.url", settings.DATABASE_URI)
# Check current alembic version
from sqlalchemy import create_engine
from alembic.runtime.environment import EnvironmentContext
engine = create_engine(settings.DATABASE_URI)
with engine.connect() as connection:
context = EnvironmentContext(alembic_cfg, connection)
current_version = context.get_current_revision()
# Upgrade alembic if current version is not the latest version
if current_version != command.get_current_head(alembic_cfg):
logger.info("Upgrading alembic on startup")
command.upgrade(alembic_cfg, "head")
logger.info("Successfully upgraded alembic on startup")
else:
logger.info("Alembic already up to date")
This code first checks the current alembic version by creating a connection to the database and using the EnvironmentContext class from the alembic library. If the current version is not the latest version, the code runs the alembic upgrade. Otherwise, it simply logs a message to indicate that the
Thanks a lot for bringing this up! I have two questions:
- doesn't alembic already do this internally at startup? I.e. if there's nothing to do it just does nothing by itself
- your PR does not include the change you suggest, but seems to revert some recent changes. are you sure your code is up to date?
@yk i am not sure what the first Q is but yes, Alembic will do nothing automatically if there are no pending migrations to apply it to if the database is up to date , Alembic will not apply any further migrations. i think the code is up to date, review it if you believe it does not add any value, ignore the merge request
I think in this case we'll leave it like it is, just because it's less code to maintain and it doesn't impact performance a lot if alembic already takes care of not upgrading if there's nothing to do.