Update line using Function and Triggers in Supabase

Guys,

I have these two tables and this relationship between them.

I need: whenever a comment is added, the evaluative_calculation column is recalculated.

I tried to do it like this:

1. Create a function to calculate the rating based on comments:

CREATE OR REPLACE FUNCTION calculate_evaluation(event_id uuid)
  RETURNS numeric AS
$$
DECLARE
  total_stars numeric := 0;
  total_comments numeric := 0;
  avg_evaluation numeric := 0;
BEGIN
  SELECT COALESCE(SUM("numberStars"), 0), COUNT(*) INTO total_stars, total_comments
  FROM public.comments
  WHERE "eventGet" = event_id;

  IF total_comments > 0 THEN
    avg_evaluation := total_stars / total_comments;
  END IF;

  RETURN avg_evaluation;
END;
$$
LANGUAGE plpgsql;
  1. Create a trigger to call a function whenever qtd_comments is updated:

CREATE OR REPLACE FUNCTION update_evaluation()
  RETURNS TRIGGER AS
$$
BEGIN
  IF NEW."qtdComments" IS DISTINCT FROM OLD."qtd_comments" THEN
    UPDATE public.events
    SET evaluative_calculation = calculate_evaluation(NEW.id)
    WHERE id = NEW.id;
  END IF;
  
  RETURN NEW;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER update_evaluation_trigger
AFTER UPDATE OF "qtd_comments" ON public.events
FOR EACH ROW
EXECUTE FUNCTION update_evaluation();

Now, whenever the qtd_comments column in the events table is updated, the trigger will call the update_evaluation function, which in turn will calculate the evaluation based on the comments associated with the event and update the evaluative_calculation column. Be sure to adapt the code as needed to suit your specific application and environment.

The issue is that for some reason this solution didn't work. Can someone help me?

Note: I don't know much about Supabase and its configurations.

1 reply