9. Database Functions, Triggers & Webhooks
Server-Side Logic That Lives in the Database
Postgres functions and triggers let you embed business logic directly in the database, guaranteeing it runs for every operation regardless of which client, API, or tool made the change. Supabase adds Database Webhooks on top, letting you fire HTTP requests (including Edge Functions) in response to table events.
Functions and triggers are the secret weapons of advanced Supabase developers. Functions are reusable blocks of logic that run in the database. They can be called from the client, from triggers, or from other functions. Triggers are functions that run automatically when certain events happen — INSERT, UPDATE, DELETE. They're perfect for audit logs, automatic updates, and complex validation. Webhooks are HTTP callbacks that fire when a table event occurs. The combination of functions, triggers, and webhooks gives you complete control over your data's behavior. You can implement business rules that are guaranteed to run, no matter how the data is modified. This is essential for financial systems, compliance, and any application where data integrity is critical.
Postgres Functions (PL/pgSQL)
PL/pgSQL is Postgres's procedural language. It provides variables, loops, conditionals, and error handling. Functions can be used for complex business logic that would be difficult or impossible with SQL alone. They're also faster than doing multiple round trips from the client. The SECURITY DEFINER attribute makes the function run with the function owner's permissions. This allows controlled privilege escalation for specific operations. Functions can return tables, JSON, or scalar values. They can also call other functions and raise exceptions. Use functions for operations that require multiple steps to succeed or fail atomically. For example, placing an order requires checking stock, updating inventory, creating the order, and creating order items. This should all happen in one transaction. A function ensures this atomicity.
-- Function to calculate order total and update inventory atomically CREATE OR REPLACE FUNCTION place_order( p_user_id UUID, p_items JSONB ) RETURNS UUID AS $$ DECLARE v_order_id UUID; v_item RECORD; v_price NUMERIC; v_stock INT; BEGIN INSERT INTO orders (user_id, status) VALUES (p_user_id, 'pending') RETURNING id INTO v_order_id; FOR v_item IN SELECT * FROM jsonb_to_recordset(p_items) AS x(product_id BIGINT, quantity INT) LOOP SELECT price, stock INTO v_price, v_stock FROM products WHERE id = v_item.product_id FOR UPDATE; IF v_stock < v_item.quantity THEN RAISE EXCEPTION 'Insufficient stock for product %', v_item.product_id; END IF; UPDATE products SET stock = stock - v_item.quantity WHERE id = v_item.product_id; INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (v_order_id, v_item.product_id, v_item.quantity, v_price); END LOOP; UPDATE orders SET status = 'confirmed' WHERE id = v_order_id; RETURN v_order_id; END; $$ LANGUAGE plpgsql SECURITY DEFINER;
Triggers: Automated Reactions
Triggers run automatically when certain operations occur. They can be BEFORE or AFTER the operation. BEFORE triggers can modify the data being inserted or updated. This is useful for auto-populating fields like updated_at. AFTER triggers are used for side effects like audit logging or notifications. INSTEAD OF triggers work on views — they let you implement custom logic for operations on views. Triggers are powerful but should be used carefully. Too many triggers can make the database hard to debug. Always document triggers thoroughly. Use triggers for automatic behaviors that are guaranteed to run, like updating timestamps or logging changes. Use SECURITY DEFINER for triggers that need elevated permissions.
-- Auto-update updated_at on any row change CREATE OR REPLACE FUNCTION set_updated_at() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER update_profiles_updated_at BEFORE UPDATE ON profiles FOR EACH ROW EXECUTE FUNCTION set_updated_at();
Fires before the operation. Can modify NEW to change the data that gets written. Used for validation and auto-population.
Fires after the operation. OLD and NEW are both available. Used for auditing, denormalization, and notifications.
Replaces the operation entirely. Used on views to make them writable.
Database Webhooks
Supabase Database Webhooks let you trigger HTTP requests when specific table events occur. The webhook payload includes the full row data (old and new values) in JSON format. Webhooks are asynchronous — the transaction commits before the webhook fires. This means the webhook won't block your database operations. Webhooks are perfect for sending emails, calling external APIs, or any operation that shouldn't be part of the database transaction. Use the pg_net extension to make HTTP requests from Postgres. The http_request function takes a URL, method, headers, and body. Always include authentication headers for security. Webhooks are a powerful way to integrate Supabase with external services.
-- Enable pg_net extension (required for webhooks) CREATE EXTENSION IF NOT EXISTS pg_net; -- Create a webhook that fires an Edge Function when a new order is placed SELECT supabase_functions.http_request( 'https://[ref].supabase.co/functions/v1/process-order', 'POST', '{"Content-Type": "application/json", "Authorization": "Bearer [service_role_key]"}', to_jsonb(NEW)::text, '5000' );
Knowledge Check
Ready to test your understanding of 9. Database Functions, Triggers & Webhooks?