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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
-- Performance fix for per-tenant searchIndex_<companyId> tables.
--
-- Problem (from Supabase performance advisor): 2,283 "unused index" warnings
-- against these tables. The GIN index on searchVector is never used because
-- search_company_index() combines `ILIKE ... OR ILIKE ... OR @@` in its WHERE
-- clause, which forces a seq scan every time. The auxiliary entityType_idx and
-- updatedAt_idx are unreachable even after the GIN path is fixed (entityType
-- filter is low-cardinality; updatedAt is defeated by the ORDER BY CASE).
--
-- Changes:
-- 1. Rewrite search_company_index to go through the GIN index via
-- to_tsquery(lexeme:* & lexeme:* & ...) + @@, ranked by ts_rank_cd. The
-- :* suffix preserves the prefix-matching UX of the old ILIKE path
-- (typing "wid" still finds "widget") while staying on the GIN access
-- path. title/description are already materialized into searchVector by
-- the sync triggers.
-- 2. Drop entityType_idx and updatedAt_idx from every existing tenant table.
-- 3. Stop creating those two indexes for newly onboarded tenants.
--
-- Write amplification drops from 3 indexes to 1 per row on every
-- upsert_to_search_index call (triggered by 15+ source tables).
-- 1. Rewrite search_company_index to use the GIN index with prefix matching.
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;
BEGIN
v_table_name := 'searchIndex_' || p_company_id;
-- Strip every character that could be interpreted as a tsquery operator
-- (&, |, !, parens, colon, backslash, quotes) before we hand the tokens
-- to to_tsquery. Hyphens and underscores are preserved for part-number
-- style tokens; the text search parser will handle them.
v_sanitized := regexp_replace(coalesce(trim(p_query), ''), '[^[:alnum:][:space:]_-]', ' ', 'g');
-- Build `tok1:* & tok2:* & ...` so every token matches as a prefix. This
-- restores the "type-as-you-go" behavior the old ILIKE branches provided
-- while keeping the query on the GIN index.
SELECT string_agg(tok || ':*', ' & ')
INTO v_tsquery_text
FROM regexp_split_to_table(v_sanitized, '\s+') AS tok
WHERE length(tok) > 0;
IF v_tsquery_text IS NULL OR v_tsquery_text = '' THEN
RETURN;
END IF;
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."searchVector" @@ q.query
AND si."entityType" = ANY($2)
ORDER BY
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;
END;
$$ LANGUAGE plpgsql SECURITY INVOKER;
-- 2. Drop the two redundant indexes from existing tenants.
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('DROP INDEX IF EXISTS %I', v_table_name || '_entityType_idx');
EXECUTE format('DROP INDEX IF EXISTS %I', v_table_name || '_updatedAt_idx');
END LOOP;
END $$;
-- 3. Stop creating the two dropped indexes on future tenants. Only the GIN
-- fts_idx is retained because it is the sole access path for the query above.
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');
-- Only GIN on searchVector is retained. entityType_idx and updatedAt_idx
-- were dropped in 20260419120001 after verifying they were never used.
EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("searchVector")',
v_table_name || '_fts_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);
-- Register the company in the registry
INSERT INTO "searchIndexRegistry" ("companyId")
VALUES (p_company_id)
ON CONFLICT ("companyId") DO NOTHING;
END;
$$ LANGUAGE plpgsql SECURITY INVOKER;