PostgreSQL触发器在UPDATE上触发,而不是在INSERT上触发

时间:2012-02-29 13:00:49

标签: ruby-on-rails postgresql triggers full-text-search

我有这个recommendations表:

                                           Table "public.recommendations"
        Column         |            Type             |                          Modifiers                           
-----------------------+-----------------------------+--------------------------------------------------------------
 id                    | integer                     | not null default nextval('recommendations_id_seq'::regclass)
 comment_on_provider   | text                        | 
 created_at            | timestamp without time zone | not null
 updated_at            | timestamp without time zone | not null
 search_vector         | tsvector                    | 
Indexes:
    "recommendations_pkey" PRIMARY KEY, btree (id)
    "recommendations_search_vector_idx" gin (search_vector)
Triggers:
    recommendations_vector_update BEFORE INSERT OR UPDATE ON recommendations FOR EACH ROW EXECUTE PROCEDURE search_trigger()

和此触发器

  CREATE OR REPLACE FUNCTION search_trigger() RETURNS trigger AS $$
  DECLARE
    search TEXT;
    links_title TEXT;
    links_description TEXT;
  begin
    SELECT string_agg(title, ' ') INTO links_title 
    FROM links
    INNER JOIN recommendations
    ON new.link_id = links.id;

    SELECT string_agg(description, ' ') INTO links_description 
    FROM links
    INNER JOIN recommendations
    ON new.link_id = links.id;

    search := '';
    search := search || ' ' || coalesce(new.comment_on_provider);
    search := search || ' ' || links_title;
    search := search || ' ' || links_description;

    new.search_vector := to_tsvector(search); 
    return new;
  end
  $$ LANGUAGE plpgsql;

  CREATE TRIGGER recommendations_vector_update 
    BEFORE INSERT OR UPDATE ON recommendations
  FOR EACH ROW EXECUTE PROCEDURE
    search_trigger();

当我向recommendations表插入记录时,触发器不会触发,search_vector设置为空。

但是,当我更新任何记录时,它会触发,search_vector会更新预期值。

如何使触发器在INSERT上运行?

1 个答案:

答案 0 :(得分:2)

我认为在INSERT的情况下,分配给search变量的表达式中的一些变量是NULL。最有可能的是new.comment_on_provider但更好的检查。