GeneIT/geneit_backend/migrations/2023-05-24-102711_create_users/up.sql

71 lines
1.5 KiB
MySQL
Raw Normal View History

2023-06-15 16:00:31 +00:00
-- Create tables
2023-05-24 11:52:24 +00:00
CREATE TABLE users (
id SERIAL PRIMARY KEY,
2023-05-24 12:38:18 +00:00
name VARCHAR(30) NOT NULL,
2023-05-24 11:52:24 +00:00
email VARCHAR(255) NOT NULL,
password VARCHAR NULL,
time_create BIGINT NOT NULL,
2023-06-06 07:47:52 +00:00
reset_password_token VARCHAR(150) NULL,
2023-05-24 11:52:24 +00:00
time_gen_reset_token BIGINT NOT NULL DEFAULT 0,
2023-06-06 07:47:52 +00:00
delete_account_token VARCHAR(150) NULL,
time_gen_delete_account_token BIGINT NOT NULL DEFAULT 0,
2023-05-24 11:52:24 +00:00
time_activate BIGINT NOT NULL DEFAULT 0,
active BOOLEAN NOT NULL DEFAULT TRUE,
admin BOOLEAN NOT NULL DEFAULT FALSE
2023-06-15 16:00:31 +00:00
);
2023-06-16 15:51:51 +00:00
CREATE TABLE families (
2023-06-15 16:00:31 +00:00
id SERIAL PRIMARY KEY,
time_create BIGINT NOT NULL,
name VARCHAR(30) NOT NULL,
invitation_code VARCHAR(7) NOT NULL
);
2023-06-16 15:51:51 +00:00
CREATE TABLE memberships (
2023-06-15 16:00:31 +00:00
user_id integer NOT NULL REFERENCES users,
family_id integer NOT NULL REFERENCES families,
time_create BIGINT NOT NULL,
2023-06-16 15:51:51 +00:00
is_admin BOOLEAN NOT NULL DEFAULT FALSE,
2023-06-15 16:00:31 +00:00
PRIMARY KEY(user_id, family_id)
2023-06-19 17:00:35 +00:00
);
-- Create views
create view
families_memberships
as
select
m.user_id ,
m.family_id,
m.is_admin ,
f."name",
f.time_create,
f.invitation_code,
cm.num as count_members,
ca.num as count_admins
from
memberships m
left join families f on
f.id = m.family_id
-- count members
left join (
select
family_id ,
count(*) as num
from
memberships m
group by
family_id) cm on
cm.family_id = m.family_id
-- count admins
left join (
select
family_id ,
count(*) as num
from
memberships m
where
m.is_admin = true
group by
family_id) ca on
ca.family_id = m.family_id