Create view to load memberships

This commit is contained in:
Pierre HUBERT 2023-06-19 19:00:35 +02:00
parent c2e93aebbe
commit 0ef722d29f
4 changed files with 55 additions and 1 deletions

View File

@ -1,4 +1,5 @@
-- This file should undo anything in `up.sql` -- This file should undo anything in `up.sql`
drop view if exists families_memberships ;
DROP table IF EXISTS memberships ; DROP table IF EXISTS memberships ;
DROP table IF EXISTS families; DROP table IF EXISTS families;
DROP table IF EXISTS users; DROP table IF EXISTS users;

View File

@ -28,4 +28,44 @@ CREATE TABLE memberships (
is_admin BOOLEAN NOT NULL DEFAULT FALSE, is_admin BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY(user_id, family_id) PRIMARY KEY(user_id, family_id)
); );
-- 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

View File

@ -5,5 +5,6 @@ pub mod controllers;
pub mod services; pub mod services;
pub mod utils; pub mod utils;
pub mod manual_schema;
pub mod models; pub mod models;
pub mod schema; pub mod schema;

View File

@ -0,0 +1,12 @@
diesel::table! {
families_memberships (user_id, family_id) {
user_id -> Int4,
family_id -> Int4,
name -> Varchar,
time_create -> Int8,
is_admin -> Bool,
invitation_code -> Varchar,
count_members -> Int4,
count_admins -> Int4,
}
}