``` -- inserts a row into public.users create OR R...
# sql
d
Copy code
-- inserts a row into public.users
create OR REPLACE function public.handle_new_user() 
returns trigger 
language plpgsql 
security definer set search_path = public
as $$
begin
  insert into public.profiles (id, raw_user_meta_data)
  values (new.id, new.raw_user_meta_data);
  return new;
end;
$$;

-- trigger the function every time a user is created
DROP TRIGGER IF EXISTS on_auth_user_created on auth.users;
create trigger on_auth_user_created
  after insert on auth.users
  for each row execute procedure public.handle_new_user();
g
You need a similar function triggered on “update after”. You then replace the insert with an update something like: ‘’’ update public.profiles set raw_user_meta_data = new.raw_user_meta_data where id = new.id; ‘’’
In thinking about it you might want to do a check if new.meta... != old.meta… around the update operation as you don't need to waste updates for other changes to the row.
d
Hii @User Thank you it works now but I was unable to make the condition check like mention. below is what I tried.
Copy code
begin
  update public.profiles
  set raw_user_meta_data = new.raw_user_meta_data
  where id = new.id and not raw_user_meta_data = new.raw_user_meta_data;
  return new;
end;
g
I would do it like:
Copy code
if OLD.raw_user_meta_data != NEW.raw_user_meta_data then
  update public.profiles 
  set ....
   where id = new.id ;
end if;
d
does this OLD available automatically.?
g
Yes, for update trigger
d
Thank you, Do you have youtube channel.? can you suggest some referance to learn
plpgsql
g
Just google, Here is a pretty detailed one: https://www.postgresqltutorial.com/postgresql-plpgsql/