Using tsvector update trigger in Postgres trigger Using tsvector update trigger in Postgres trigger postgresql postgresql

Using tsvector update trigger in Postgres trigger


This is what I ended up with:

CREATE FUNCTION albums_vector_update() RETURNS TRIGGER AS $$BEGIN    IF TG_OP = 'INSERT' THEN        new.search_vector = to_tsvector('pg_catalog.english', COALESCE(NEW.name, ''));    END IF;    IF TG_OP = 'UPDATE' THEN        IF NEW.name <> OLD.name THEN            new.search_vector = to_tsvector('pg_catalog.english', COALESCE(NEW.name, ''));        END IF;    END IF;    RETURN NEW;END$$ LANGUAGE 'plpgsql';CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE ON albumsFOR EACH ROW EXECUTE PROCEDURE albums_vector_update();


An alternative could be something like distinct from, it really helped me a few times. Untested code though.

CREATE TRIGGER albums_vector_update BEFORE INSERT OR UPDATE ON albumsFOR EACH ROW WHEN (OLD.name IS DISTINCT FROM NEW.name)EXECUTE PROCEDURE tsvector_update_trigger(search_vector, 'pg_catalog.english', NEW.name);


The name comparison logic needs to go into the tsvector_update_trigger procedure code.something like:

IF TG_OP = 'UPDATE' THEN    IF NEW.name <> OLD.name THEN       -- Do tsvector update    END IF;END IF;

Then create a trigger that is called before INSERT and UPDATE