1+ -- Drop the view if it already exists to make this script re-runnable
2+ DROP MATERIALIZED VIEW IF EXISTS " OrganizationStats" ;
3+
4+ -- Create the materialized view to store organization-level counts
5+ CREATE MATERIALIZED VIEW " OrganizationStats" AS
6+ SELECT
7+ o .id AS " organizationId" ,
8+ o .name AS " organizationName" ,
9+ o .slug AS " organizationSlug" ,
10+ COUNT (DISTINCT apikey .id ) AS " apiKeysCount" ,
11+ COUNT (DISTINCT audit .id ) AS " auditLogsCount" ,
12+ COUNT (DISTINCT ctrl .id ) AS " controlsCount" ,
13+ COUNT (DISTINCT fi .id ) AS " frameworkInstancesCount" ,
14+ COUNT (DISTINCT integ .id ) AS " integrationsCount" ,
15+ COUNT (DISTINCT inv .id ) AS " invitationsCount" ,
16+ COUNT (DISTINCT mem .id ) AS " membersCount" ,
17+ COUNT (DISTINCT pol .id ) AS " policiesCount" ,
18+ COUNT (DISTINCT rsk .id ) AS " risksCount" ,
19+ COUNT (DISTINCT ven .id ) AS " vendorsCount" ,
20+ COUNT (DISTINCT tsk .id ) AS " tasksCount" ,
21+ COUNT (DISTINCT cmt .id ) AS " commentsCount" ,
22+ COUNT (DISTINCT att .id ) AS " attachmentsCount" ,
23+ COUNT (DISTINCT trst." organizationId" ) AS " trustsCount" ,
24+ COUNT (DISTINCT ctx .id ) AS " contextsCount"
25+ FROM
26+ " Organization" o
27+ LEFT JOIN " ApiKey" apikey ON o .id = apikey." organizationId"
28+ LEFT JOIN " AuditLog" audit ON o .id = audit." organizationId"
29+ LEFT JOIN " Control" ctrl ON o .id = ctrl." organizationId"
30+ LEFT JOIN " FrameworkInstance" fi ON o .id = fi." organizationId"
31+ LEFT JOIN " Integration" integ ON o .id = integ." organizationId"
32+ LEFT JOIN " Invitation" inv ON o .id = inv." organizationId"
33+ LEFT JOIN " Member" mem ON o .id = mem." organizationId"
34+ LEFT JOIN " Policy" pol ON o .id = pol." organizationId"
35+ LEFT JOIN " Risk" rsk ON o .id = rsk." organizationId"
36+ LEFT JOIN " Vendor" ven ON o .id = ven." organizationId"
37+ LEFT JOIN " Task" tsk ON o .id = tsk." organizationId"
38+ LEFT JOIN " Comment" cmt ON o .id = cmt." organizationId"
39+ LEFT JOIN " Attachment" att ON o .id = att." organizationId"
40+ LEFT JOIN " Trust" trst ON o .id = trst." organizationId"
41+ LEFT JOIN " Context" ctx ON o .id = ctx." organizationId"
42+ GROUP BY o .id , o .name , o .slug ;
43+
44+ CREATE UNIQUE INDEX "idx_organization_stats_organizationId " ON " OrganizationStats" (" organizationId" );
0 commit comments