"""Workflow search provider — FTS search on workflows and workflow_instances tables.""" from __future__ import annotations import logging import uuid from typing import Any from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from app.plugins.builtins.unified_search.base_provider import BaseSearchProvider logger = logging.getLogger(__name__) class WorkflowSearchProvider(BaseSearchProvider): """Search provider for Workflow entities (definitions and instances).""" entity_type = "workflow" supports_fts = True supports_vector = False async def _search_fts_filtered( self, db: AsyncSession, tsquery: str, tenant_id: uuid.UUID, limit: int, visible_ids: set[uuid.UUID] | None, ) -> list[dict[str, Any]]: """Full-text search on workflows name/description and workflow_instances status.""" if visible_ids is not None: sql = text( """ SELECT w.id, w.tenant_id, w.name, w.description, w.trigger_event, w.is_active, ts_rank( to_tsvector('pg_catalog.german', coalesce(w.name, '') || ' ' || coalesce(w.description, '')), to_tsquery('pg_catalog.german', :q) ) AS rank FROM workflows w WHERE w.tenant_id = :tid AND to_tsvector('pg_catalog.german', coalesce(w.name, '') || ' ' || coalesce(w.description, '')) @@ to_tsquery('pg_catalog.german', :q) AND w.id = ANY(:visible_ids) ORDER BY rank DESC LIMIT :lim """ ) result = await db.execute( sql, { "q": tsquery, "tid": tenant_id, "lim": limit, "visible_ids": list(visible_ids), }, ) else: sql = text( """ SELECT w.id, w.tenant_id, w.name, w.description, w.trigger_event, w.is_active, ts_rank( to_tsvector('pg_catalog.german', coalesce(w.name, '') || ' ' || coalesce(w.description, '')), to_tsquery('pg_catalog.german', :q) ) AS rank FROM workflows w WHERE w.tenant_id = :tid AND to_tsvector('pg_catalog.german', coalesce(w.name, '') || ' ' || coalesce(w.description, '')) @@ to_tsquery('pg_catalog.german', :q) ORDER BY rank DESC LIMIT :lim """ ) result = await db.execute( sql, {"q": tsquery, "tid": tenant_id, "lim": limit}, ) rows = result.mappings().all() return [dict(r) for r in rows] async def _search_vector_filtered( self, db: AsyncSession, embedding: list[float], tenant_id: uuid.UUID, limit: int, visible_ids: set[uuid.UUID] | None, ) -> list[dict[str, Any]]: """No vector support for workflows — return empty list.""" return [] async def get_embedding_text( self, db: AsyncSession, entity_id: uuid.UUID, tenant_id: uuid.UUID ) -> str: """Get text for embedding generation — returns workflow name + description.""" sql = text( """ SELECT name, description FROM workflows WHERE id = :eid AND tenant_id = :tid """ ) result = await db.execute(sql, {"eid": entity_id, "tid": tenant_id}) row = result.mappings().first() if not row: return "" parts = [row.get("name", ""), row.get("description", "")] return " ".join(str(p) for p in parts if p) def to_search_result(self, entity: object) -> dict[str, Any]: """Convert workflow to search result dict.""" if isinstance(entity, dict): entity_id = str(entity.get("id", "")) name = entity.get("name", "") description = entity.get("description", "") trigger_event = entity.get("trigger_event", "") is_active = entity.get("is_active", True) score = entity.get("rank", 0.0) else: entity_id = str(getattr(entity, "id", "")) name = getattr(entity, "name", "") description = getattr(entity, "description", "") trigger_event = getattr(entity, "trigger_event", "") is_active = getattr(entity, "is_active", True) score = getattr(entity, "rank", 0.0) return { "entity_type": self.entity_type, "entity_id": entity_id, "title": name, "snippet": description or "", "score": float(score) if score else 0.0, "data": { "trigger_event": trigger_event, "is_active": is_active, }, }