46 lines
2.1 KiB
SQL
46 lines
2.1 KiB
SQL
-- Hot-path performance indexes (TenantUser / GroupUser / OutboundEmail).
|
|
--
|
|
-- All statements are guarded with IF NOT EXISTS so the migration is reproducible
|
|
-- against a fresh DB and safe to replay (P3018 / lexicographic-ordering lesson):
|
|
-- a previous branch could already have created an identically named index.
|
|
--
|
|
-- The TenantUser (tenantId, userId) UNIQUE index additionally fails loudly if the
|
|
-- table already holds duplicate (tenantId, userId) rows, mirroring the existing
|
|
-- user_role / group_user uniqueness migrations -- the app already treats a
|
|
-- (tenant, user) pair as a single membership (getTenantMember/getTenantUserByIds
|
|
-- use findFirst), so duplicates would be a data anomaly, not a supported state.
|
|
--
|
|
-- Forward-only. Inverse (manual rollback):
|
|
-- DROP INDEX IF EXISTS "TenantUser_tenantId_userId_key";
|
|
-- DROP INDEX IF EXISTS "TenantUser_tenantId_status_idx";
|
|
-- DROP INDEX IF EXISTS "TenantUser_userId_idx";
|
|
-- DROP INDEX IF EXISTS "OutboundEmail_tenantId_sentAt_idx";
|
|
-- DROP INDEX IF EXISTS "GroupUser_groupId_idx";
|
|
-- DROP INDEX IF EXISTS "GroupUser_userId_idx";
|
|
|
|
-- TenantUser: reverse-lookup by user and tenant+status scans.
|
|
CREATE INDEX IF NOT EXISTS "TenantUser_userId_idx" ON "TenantUser"("userId");
|
|
CREATE INDEX IF NOT EXISTS "TenantUser_tenantId_status_idx" ON "TenantUser"("tenantId", "status");
|
|
|
|
-- TenantUser: one membership row per (tenant, user). Guard against pre-existing duplicates.
|
|
DO $$
|
|
BEGIN
|
|
IF EXISTS (
|
|
SELECT 1
|
|
FROM "TenantUser"
|
|
GROUP BY "tenantId", "userId"
|
|
HAVING COUNT(*) > 1
|
|
) THEN
|
|
RAISE EXCEPTION 'Cannot add TenantUser uniqueness: duplicate tenantId/userId rows exist';
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS "TenantUser_tenantId_userId_key" ON "TenantUser"("tenantId", "userId");
|
|
|
|
-- OutboundEmail: tenant-scoped time-ordered listing.
|
|
CREATE INDEX IF NOT EXISTS "OutboundEmail_tenantId_sentAt_idx" ON "OutboundEmail"("tenantId", "sentAt");
|
|
|
|
-- GroupUser: reverse lookups by user and by group.
|
|
CREATE INDEX IF NOT EXISTS "GroupUser_userId_idx" ON "GroupUser"("userId");
|
|
CREATE INDEX IF NOT EXISTS "GroupUser_groupId_idx" ON "GroupUser"("groupId");
|