I have a pgsql trigger
and a trigger function
. Works when updating a previous record and does not work when inserting a new record. Ideally, the text_search
column should be populated with the tsvector
data mentioned.
The id
column of the table idea
is of bigserial
and some of the other fields added to text_search are nullable
if that's important.
Trigger
CREATE TRIGGER update_idea_text_search
BEFORE INSERT OR UPDATE
ON prod.idea
FOR EACH ROW
EXECUTE FUNCTION prod.update_idea_text_search();
Trigger Function
CREATE OR REPLACE FUNCTION prod.update_idea_text_search()
RETURNS trigger
LANGUAGE 'plpgsql'
COST 100
VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE text_search TSVECTOR;
BEGIN
SELECT
((
setweight(to_tsvector('english'::regconfig, COALESCE(title, ''::text)), 'A'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(subtitle, ''::text)), 'A'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(strategy, ''::text)), 'A'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(summary, ''::text)), 'B'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(conditions, ''::text)), 'B'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(strategy_data::text, ''::text)), 'B'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(tags::text, ''::text)), 'A'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(id::text, ''::text)), 'B'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(buy::text, ''::text)), 'C'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(sell::text, ''::text)), 'C'::"char")
))
INTO text_search
FROM
prod.idea
WHERE
idea.id = NEW.id;
NEW.text_search := coalesce(text_search, '');
RETURN NEW;
END
$BODY$;
If any more information is required let me know and other comments/suggestions are welcome!