When using Supabase, I need to add the identifier of a newly registered user to the users
table. Here’s a basic function I’m currently using:
create function public.add_user()
returns trigger
language plpgsql
security definer set search_path = public
as $$
begin
insert into public.users (id)
values (new.id);
return new;
end;
$$;
create trigger after_user_created
after insert on auth.users
for each row execute procedure public.add_user();
Additionally, I want to insert entries into two other tables: the organisations
table, which should have a unique id
and default name
as My first org
, and the org_users
table, which will hold a unique id
, user_id
from the users
table, org_id
from the organisations
table, and role_id
from the org_roles
table that corresponds to the role of an owner
.
I acknowledge that there may be similar questions out there, yet the responses haven’t aligned with what I’m attempting to achieve using my understanding of SQL or Postgres.
While it’s possible to handle this client-side without issues, I believe that figuring out how to accomplish this in SQL is beneficial for others as well.
What steps do I need to take to create a single function that performs the following tasks?
- Create a new entry in the
users
table using theauth.users.id
, - Create a new entry in the
organisations
table with a uniqueid
andname
set toMy first org
, - Lastly, create an entry in the
org_users
table with a uniqueid
, theuser_id
from theusers
table, and theorg_id
from theorganisations
table.
Here’s a SQL snippet illustrating how I envision this working:
WITH inserted_user AS (
insert into public.users (id) values (new.id) returning new
),
new_org AS (
insert into public.organisations (id, name) values (uuid_generate_v4(), 'My first org') returning id
)
insert into public.org_users (user_id, org_id)
select inserted_user.id, new_org.id from inserted_user, new_org;
return NULL;