Search code examples
triggerssupabasesupabase-database

Call Edge Function from Database Trigger


I am using supabase and I try to implement some warning functionality. I want to send an E-Mail when a value drops under a specific value.

I know about database triggers but I am not sure about two things.

  1. How can I check if the value is dropping below the threshold the first time? Is there a chance to get the before and after value of a change in a table row?
  2. Can I call an Edge Function from the trigger or from a database function that is called from the trigger where I can send the E-Mail?

Solution

  • Your design is possible.

    About point 1:
    postgres trigger-functions can see the OLD and NEW value as special variables. See here: https://www.postgresql.org/docs/current/plpgsql-trigger.html They may be null though, depending on the operation (insert doesn't have a OLD, delete has no NEW). You can also access the operation that triggered your trigger using TG_OP, see here: PostgreSQL: Checking for NEW and OLD in a function for a trigger

    About point 2:
    Postgres-triggers can make http-requests with the pg_net-extension, which you can use to trigger your edge-function with the right data. It's a bit bare-bones, but it works. https://supabase.com/docs/guides/database/extensions/pg_net