Need Assistance with a Postgres Trigger and Function

ぃ、小莉子 提交于 2019-12-12 12:06:10

问题


I have a lookup table that holds a column of sources (from various hardcoded campaigns captured through a webservice API I created) and the respective brands that should be associated with them. This is so I can give a brand to records where brand is null - so that they can be welcomed with a certain template through a marketing automation tool.

I'm eventually deprecating this API and replacing it with one where brand is required, but in the meantime I have to craft a temporary solution until I give all my brand teams time to change their API calls.

I wrote this function:

CREATE OR REPLACE FUNCTION public.brand_lookup(IN i_brand TEXT )
  RETURNS SETOF RECORD VOLATILE AS
$$
BEGIN
   RETURN QUERY
     UPDATE subscriber
     SET brand = (SELECT brand FROM brand_translation
                  WHERE source = subscriber.source);
END;
$$
LANGUAGE plpgsql;

And a trigger to fire the function when a record is inserted:

CREATE TRIGGER brand_translation 
  AFTER INSERT ON subscriber
  FOR EACH ROW EXECUTE PROCEDURE public.brand_lookup();

But my trigger comes back with an error that "ERROR: function public.brand_lookup() does not exist" (but it created successfully)". Besides the fact that my trigger doesn't see my function, will that function do what I'm intending? I'm fairly noob at functions (as you can probably tell).


回答1:


It might work like this:

CREATE OR REPLACE FUNCTION public.f_brand_lookup()
   RETURNS trigger AS
$func$
BEGIN
   SELECT INTO NEW.brand
          bt.brand
   FROM   brand_translation bt
   WHERE  bt.source = NEW.source;

   RETURN NEW;
END
$func$
LANGUAGE plpgsql;

CREATE TRIGGER brand_insert_before_lookup
BEFORE INSERT ON subscriber
FOR EACH ROW EXECUTE PROCEDURE public.f_brand_lookup();

There is just too much completely wrong with your example.
You need to start by studying the basics. As always, I suggest the very fine manual.
Start here and here.




回答2:


Postres allows for overloading of functions depending on the input parameters-- so when you call public.brand_lookup() with no parameters, the function you created-- public.brand_lookup(text)-- is not found. I think you need to pass the necessary parameter in the call to the function, or remove the parameter in the function definition.



来源:https://stackoverflow.com/questions/15625409/need-assistance-with-a-postgres-trigger-and-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!