auth 스키마에서 관리하던 user 정보를 public 스키마에서 관리하려고 한다.
SQL Editor로 실행한 코드 정리.
요구사항
id: auth.users의 id(UUID)를 기본 키로 설정
email: 회원 이메일 (중복 방지 - auth에 저장된 user id)
nickname: 회원가입 시 입력한 닉네임 저장
created_at: 생성 시간 <- 회원가입 시점
on delete cascade: auth.users에서 유저가 삭제되면 public.users도 자동 삭제
supabase를 이용한 회원가입 시에 유저의 metadata를 options로 함께 받고 있다. 해당 정보가 auth 스키마에 들어있어서, 이러한 내용들을 public으로 가져오려는 것.
create table public.users (
id uuid primary key references auth.users(id) on delete cascade,
email text unique not null,
nickname text,
created_at timestamp not null
);
create function sync_users_to_public()
returns trigger as $$
begin
insert into public.users (id, email, nickname, created_at)
values (
new.id,
new.email,
new.raw_user_meta_data->>'nickname',
new.created_at
)
on conflict (id) do update
set nickname = excluded.nickname;
return new;
end;
$$ language plpgsql security definer;
create trigger on_auth_user_created
after insert on auth.users
for each row execute function sync_users_to_public();
여기까지 수행한 결과, 기존의 데이터는 연동되지 않고 새로 회원가입한 유저부터 값이 들어오는 것을 확인할 수 있다.
외래키가 이렇게 설정되어 있다.