I am trying to have a trigger refresh a materialized view when a subscriber table gets updated. In the Postgresql Docs, under typical use-cases for logical replication lists "Firing triggers for individual changes as they arrive on the subscriber."
We recently set up logical replication working between two different database instances on google cloud sql. It is for about 30 tables on the publisher, updating our subscriber. It has been working flawlessly. Really impressive.
One of the tables in on the subscriber instance, revolves around pricing, table name is product_pricelist_item
.
When a employee updates a the price of a product, this change is reflected in the subscriber in basically real-time.
We have setup a view, select * from v_pricing
, to get pricing information on the subscriber.
I want to cache the results with materialized view which we setup, select * from mv_pricing
.
I can refresh the materialize view manually and also with a cron statement every 15 minutes.
However, what I would like to move to, but I haven't been successful, is refreshing the materialized view (mv_pricing) with the below trigger setup [A].
I have tried the below statements [B], which actually stops the subscription from staying up-to-date and still does not refresh the materialized view. I have dropped the trigger so [B] is no longer in effect and recreated using [A] and the real-time updates are back in effect on the subscriber.
Has anyone had success with this process or see anything I could be missing?
Thank you.
-- [A] Trigger Setup
CREATE OR REPLACE FUNCTION refresh_mv_pricing()
RETURNS trigger AS $$
BEGIN
REFRESH MATERIALIZED VIEW CONCURRENTLY public.mv_pricing;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER trg_refresh_mv_pricing
AFTER INSERT OR UPDATE OR DELETE ON public.product_pricelist_item
FOR EACH ROW
EXECUTE FUNCTION refresh_mv_pricing();
-- [B] Has not worked, currently not in effect.
alter table product_pricelist_item enable always trigger trg_refresh_mv_pricing;
alter table product_pricelist_item enable replica trigger trg_refresh_mv_pricing;