Learn how to set up and test PostgreSQL triggers in Supabase. This guide walks you through creating projects, tables, trigger functions, and automating logs.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up a Supabase Project
Begin by setting up a Supabase project. If you don't have an account, sign up at Supabase. Once logged in, create a new project by following these steps:
This will set up a new Supabase project with its own dedicated PostgreSQL database.
Step 2: Access the Supabase Dashboard
Once the project is ready, you will be redirected to the Supabase dashboard:
Step 3: Create a Table
To work with triggers, you'll first need a table. Create a new table using SQL commands:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
);
Step 4: Create a Trigger Function
Create a trigger function that will execute a specific action automatically:
CREATE FUNCTION log_user_insertion()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO user_logs (user_id, action, created\_at)
VALUES (NEW.id, 'insert', NOW());
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
user_logs
table.
Step 5: Create the User Logs Table
Ensure you have a table to store trigger logs:
CREATE TABLE user\_logs (
id SERIAL PRIMARY KEY,
user\_id INTEGER NOT NULL,
action TEXT NOT NULL,
created\_at TIMESTAMP NOT NULL
);
user_logs
table.
Step 6: Attach the Trigger to the Users Table
Now, attach the trigger function to the users
table:
CREATE TRIGGER after_user_insert
AFTER INSERT ON users
FOR EACH ROW EXECUTE FUNCTION log_user_insertion();
log_user_insertion
function is executed after every row insertion into the users
table.
Step 7: Test the Trigger
Insert a new record into the users
table to test if the trigger works:
INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]');
user_logs
table to see if the log has been created:
SELECT \* FROM user\_logs;
users
is recorded.
Step 8: Manage and Modify Triggers
To manage or modify triggers, navigate to the SQL Editor:
DROP TRIGGER IF EXISTS after_user_insert ON users;
Conclusion
You've successfully set up and tested a PostgreSQL trigger within your Supabase project. Use this approach to automate database operations and maintain data consistency across your project.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.