diff --git a/src/backend/langflow/alembic/versions/eb5866d51fd2_change_columns_to_be_nullable.py b/src/backend/langflow/alembic/versions/eb5866d51fd2_change_columns_to_be_nullable.py index 10d503e60..cb126c926 100644 --- a/src/backend/langflow/alembic/versions/eb5866d51fd2_change_columns_to_be_nullable.py +++ b/src/backend/langflow/alembic/versions/eb5866d51fd2_change_columns_to_be_nullable.py @@ -9,6 +9,7 @@ from typing import Sequence, Union from alembic import op import sqlalchemy as sa +from sqlalchemy import exc import sqlmodel # noqa: F401 # revision identifiers, used by Alembic. @@ -20,16 +21,21 @@ depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### + connection = op.get_bind() try: op.drop_table("flowstyle") with op.batch_alter_table("component", schema=None) as batch_op: batch_op.drop_index("ix_component_frontend_node_id") batch_op.drop_index("ix_component_name") + except exc.SQLAlchemyError: + connection.execute("ROLLBACK") except Exception: pass try: op.drop_table("component") + except exc.SQLAlchemyError: + connection.execute("ROLLBACK") except Exception: pass # ### end Alembic commands ### diff --git a/src/backend/langflow/services/database/manager.py b/src/backend/langflow/services/database/manager.py index c743387eb..7465c804f 100644 --- a/src/backend/langflow/services/database/manager.py +++ b/src/backend/langflow/services/database/manager.py @@ -115,7 +115,35 @@ class DatabaseService(Service): return True + def init_alembic(self): + logger.info("Initializing alembic") + alembic_cfg = Config() + alembic_cfg.set_main_option("script_location", str(self.script_location)) + alembic_cfg.set_main_option("sqlalchemy.url", self.database_url) + command.stamp(alembic_cfg, "head") + logger.info("Alembic initialized") + def run_migrations(self): + # First we need to check if alembic has been initialized + # If not, we need to initialize it + # 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 + with Session(self.engine) as session: + # If the table does not exist it throws an error + # so we need to catch it + try: + session.execute("SELECT * FROM alembic_version") + except Exception: + logger.info("Alembic not initialized") + try: + self.init_alembic() + except Exception as exc: + logger.error(f"Error initializing alembic: {exc}") + raise RuntimeError("Error initializing alembic") from exc + else: + logger.info("Alembic already initialized") + logger.info(f"Running DB migrations in {self.script_location}") alembic_cfg = Config() alembic_cfg.set_main_option("script_location", str(self.script_location))