From be14d4558903f115ca79c3532de8ad7ebc72c9f7 Mon Sep 17 00:00:00 2001 From: Gabriel Luiz Freitas Almeida Date: Wed, 9 Aug 2023 10:28:41 -0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(utils.py):=20handle=20Comman?= =?UTF-8?q?dError=20when=20running=20migrations=20and=20delete=20alembic?= =?UTF-8?q?=5Fversion=20table=20if=20wrong=20revision=20in=20DB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../langflow/services/database/utils.py | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/backend/langflow/services/database/utils.py b/src/backend/langflow/services/database/utils.py index 20b2bbbb4..94bcd6651 100644 --- a/src/backend/langflow/services/database/utils.py +++ b/src/backend/langflow/services/database/utils.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING from langflow.utils.logger import logger from contextlib import contextmanager - +from alembic.util.exc import CommandError from sqlmodel import Session if TYPE_CHECKING: @@ -13,7 +13,23 @@ def initialize_database(): from langflow.services import service_manager, ServiceType database_manager = service_manager.get(ServiceType.DATABASE_MANAGER) - database_manager.run_migrations() + try: + database_manager.run_migrations() + except CommandError as exc: + if "Can't locate revision identified by" not in str(exc): + raise exc + # This means there's wrong revision in the DB + # We need to delete the alembic_version table + # and run the migrations again + logger.warning( + "Wrong revision in DB, deleting alembic_version table and running migrations again" + ) + with session_getter(database_manager) as session: + session.execute("DROP TABLE alembic_version") + database_manager.run_migrations() + except Exception as exc: + logger.error(f"Error running migrations: {exc}") + raise RuntimeError("Error running migrations") from exc database_manager.create_db_and_tables() logger.debug("Database initialized")