jean-marie/backend/migrations/20241221174355_add-person-l...

33 lines
1.4 KiB
SQL

-- Add login table
create table if not exists people (
id uuid NOT NULL DEFAULT gen_random_uuid (),
created_at timestamp without time zone NOT NULL DEFAULT now(),
created_by uuid NOT NULL,
updated_at timestamp without time zone NOT NULL DEFAULT now(),
updated_by uuid NOT NULL,
email text NOT NULL unique,
name text NOT NULL,
family_name text NOT NULL,
given_name text NOT NULL,
CONSTRAINT people_pkey PRIMARY KEY (id)
);
ALTER TABLE if exists users
ADD COLUMN IF NOT EXISTS person_id uuid REFERENCES people (id) ON DELETE SET NULL;
-- Copy accounts(users) to profiles(people)
insert into people (created_by, updated_by, email, name, family_name, given_name)
select created_by, updated_by, email, name, family_name, given_name from users
on conflict do nothing;
-- Link accounts to profiles
update users u set person_id = p.id from people p where p.email = u.email;
-- Move wishlist items from accounts to profiles
update wishlist_items wi set user_id = p.person_id from users p where p.id = wi.user_id;
-- Copy normal role from accounts to profiles
insert into user_roles (created_at, created_by, updated_at, updated_by, user_id, role_id)
select ur.created_at, ur.created_by, ur.updated_at, ur.updated_by, u.person_id, ur.role_id from user_roles ur join roles r on r.id = ur.role_id join users u on u.id = ur.user_id where r.name = 'normal'
on conflict do nothing;