Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix: use pg_trgm instead of ilike

Sidwebworks002b632807c8
diff --git a/packages/database/supabase/migrations/20260419140000_search-trigram-substring.sql b/packages/database/supabase/migrations/20260419140000_search-trigram-substring.sql
new file mode 100644
index 0000000000..22149dcd72
--- /dev/null
+++ b/packages/database/supabase/migrations/20260419140000_search-trigram-substring.sql
@@ -0,0 +1,165 @@
+-- Fix substring search for IDs like "S000269".
+--
+-- 20260419120001 moved search_company_index to a pure GIN/tsquery path with
+-- prefix matching (`to_tsquery('english', '269:*')`). That works for
+-- word-prefix lookups but not for substring hits inside a single lexeme:
+-- title "S000269" is one lexeme that starts with 's', so `269:*` never
+-- matches it, even though the user clearly expects it to.
+--
+-- Fix: add a pg_trgm GIN index on title per tenant and OR an `ILIKE '%...%'`
+-- branch into the WHERE. With the trigram index, the planner resolves ILIKE
+-- via BitmapIndexScan and combines it with the FTS bitmap — no seq scan. The
+-- raw-word / multi-word cases still flow through the FTS branch.
+
+CREATE EXTENSION IF NOT EXISTS pg_trgm;
+
+-- 1. Add the trigram index to every existing tenant table.
+DO $$
+DECLARE
+ company_record RECORD;
+ v_table_name TEXT;
+BEGIN
+ FOR company_record IN SELECT "companyId" FROM "searchIndexRegistry"
+ LOOP
+ v_table_name := 'searchIndex_' || company_record."companyId";
+ EXECUTE format(
+ 'CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("title" gin_trgm_ops)',
+ v_table_name || '_title_trgm_idx',
+ v_table_name
+ );
+ EXECUTE format(
+ 'CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("description" gin_trgm_ops)',
+ v_table_name || '_description_trgm_idx',
+ v_table_name
+ );
+ END LOOP;
+END $$;
+
+-- 2. Create the trigram index on newly onboarded tenants too.
+CREATE OR REPLACE FUNCTION create_company_search_index(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ v_table_name TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Create the search index table
+ EXECUTE format('
+ CREATE TABLE IF NOT EXISTS %I (
+ "id" BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "title" TEXT NOT NULL,
+ "description" TEXT DEFAULT '''',
+ "link" TEXT NOT NULL,
+ "tags" TEXT[] DEFAULT ''{}'',
+ "metadata" JSONB DEFAULT ''{}'',
+ "searchVector" TSVECTOR,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT %I UNIQUE ("entityType", "entityId")
+ )', v_table_name, v_table_name || '_entity_unique');
+
+ -- GIN on searchVector: FTS path (multi-word, stemmed prefix via :*).
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("searchVector")',
+ v_table_name || '_fts_idx', v_table_name);
+
+ -- GIN trigram on title: substring path (find "269" inside "S000269").
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("title" gin_trgm_ops)',
+ v_table_name || '_title_trgm_idx', v_table_name);
+
+ -- GIN trigram on description: substring path for hits that live in the body text.
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("description" gin_trgm_ops)',
+ v_table_name || '_description_trgm_idx', v_table_name);
+
+ -- Enable RLS (no SELECT policies - access via service role bypass)
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', v_table_name);
+
+ INSERT INTO "searchIndexRegistry" ("companyId")
+ VALUES (p_company_id)
+ ON CONFLICT ("companyId") DO NOTHING;
+END;
+$$ LANGUAGE plpgsql SECURITY INVOKER;
+
+-- 3. Rewrite search_company_index to use FTS + trigram-backed ILIKE in parallel.
+CREATE OR REPLACE FUNCTION search_company_index(
+ p_company_id TEXT,
+ p_query TEXT,
+ p_entity_types TEXT[],
+ p_limit INT DEFAULT 20
+)
+RETURNS TABLE (
+ id BIGINT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ title TEXT,
+ description TEXT,
+ link TEXT,
+ tags TEXT[],
+ metadata JSONB
+) AS $$
+DECLARE
+ v_table_name TEXT;
+ v_sanitized TEXT;
+ v_tsquery_text TEXT;
+ v_like_pattern TEXT;
+ v_prefix_pattern TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Strip tsquery operators; keep alphanumerics, whitespace, `_`, `-`.
+ v_sanitized := regexp_replace(coalesce(trim(p_query), ''), '[^[:alnum:][:space:]_-]', ' ', 'g');
+ v_sanitized := trim(regexp_replace(v_sanitized, '\s+', ' ', 'g'));
+
+ IF v_sanitized = '' THEN
+ RETURN;
+ END IF;
+
+ -- Build `tok1:* & tok2:* & ...` for the FTS branch (word-prefix match).
+ SELECT string_agg(tok || ':*', ' & ')
+ INTO v_tsquery_text
+ FROM regexp_split_to_table(v_sanitized, '\s+') AS tok
+ WHERE tok ~ '[[:alnum:]]';
+
+ -- Defensive fallback - should not trigger in practice since v_sanitized is
+ -- non-empty and contains at least one alnum, but keep the function robust.
+ IF v_tsquery_text IS NULL OR v_tsquery_text = '' THEN
+ RETURN;
+ END IF;
+
+ -- Substring + prefix patterns use the ORIGINAL sanitized string so users
+ -- can search by any slice of a stored title (e.g. "269" inside "S000269").
+ v_like_pattern := '%' || v_sanitized || '%';
+ v_prefix_pattern := v_sanitized || '%';
+
+ RETURN QUERY EXECUTE format('
+ WITH q AS (
+ SELECT to_tsquery(''english'', $1) AS query
+ )
+ SELECT
+ si.id,
+ si."entityType",
+ si."entityId",
+ si.title,
+ si.description,
+ si.link,
+ si.tags,
+ si.metadata
+ FROM %I si, q
+ WHERE si."entityType" = ANY($2)
+ AND (
+ si."searchVector" @@ q.query
+ OR si.title ILIKE $4
+ OR si.description ILIKE $4
+ )
+ ORDER BY
+ -- Boost rows where the title starts with the query (e.g. typing "S000"
+ -- pins "S000269" to the top).
+ CASE WHEN si.title ILIKE $5 THEN 0 ELSE 1 END,
+ ts_rank_cd(si."searchVector", q.query) DESC,
+ si.id DESC
+ LIMIT $3
+ ', v_table_name)
+ USING v_tsquery_text, p_entity_types, p_limit, v_like_pattern, v_prefix_pattern;
+END;
+$$ LANGUAGE plpgsql SECURITY INVOKER;