From b05455a9b865b7da4395387646fcaa3b4b7d09c0 Mon Sep 17 00:00:00 2001 From: cristhianzl Date: Tue, 25 Jun 2024 16:17:47 -0300 Subject: [PATCH] refactor: Ensure flow names are unique by appending a number if necessary --- src/backend/base/langflow/api/v1/flows.py | 27 ++++++++--------------- 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/src/backend/base/langflow/api/v1/flows.py b/src/backend/base/langflow/api/v1/flows.py index d735a314b..99c678151 100644 --- a/src/backend/base/langflow/api/v1/flows.py +++ b/src/backend/base/langflow/api/v1/flows.py @@ -1,4 +1,5 @@ from datetime import datetime, timezone +import re from typing import List from uuid import UUID @@ -46,8 +47,14 @@ def create_flow( select(Flow).where(Flow.name.like(f"{flow.name} (%")).where(Flow.user_id == current_user.id) # type: ignore ).all() if flows: - numbers = [int(flow.name.split("(")[1].split(")")[0]) for flow in flows] - flow.name = f"{flow.name} ({max(numbers) + 1})" + extract_number = re.compile(r"\((\d+)\)$") + numbers = [] + for flow in flows: + result = extract_number.search(flow.name) + if result: + numbers.append(int(result.groups(1)[0])) + if numbers: + flow.name = f"{flow.name} ({max(numbers) + 1})" else: flow.name = f"{flow.name} (1)" # Now check if the endpoint is unique @@ -210,22 +217,6 @@ def update_flow( db_flow.webhook = webhook_component is not None db_flow.updated_at = datetime.now(timezone.utc) - # First check if the flow.name is unique - # there might be flows with name like: "MyFlow", "MyFlow (1)", "MyFlow (2)" - # so we need to check if the name is unique with `like` operator - # if we find a flow with the same name, we add a number to the end of the name - # based on the highest number found - flow_from_db = session.exec(select(Flow).where(Flow.id == flow_id, Flow.user_id == current_user.id)).first() - if flow_from_db: - flows = session.exec( - select(Flow).where(Flow.name.like(f"{flow.name} (%")).where(Flow.user_id == current_user.id) # type: ignore - ).all() - if flows: - numbers = [int(flow.name.split("(")[1].split(")")[0]) for flow in flows] - flow.name = f"{flow.name} ({max(numbers) + 1})" - else: - flow.name = f"{flow.name} (1)" - if db_flow.folder_id is None: default_folder = session.exec(select(Folder).where(Folder.name == DEFAULT_FOLDER_NAME)).first() if default_folder: