53 lines
2.8 KiB
TypeScript
53 lines
2.8 KiB
TypeScript
import { readFile } from "node:fs/promises";
|
|
import { resolve } from "node:path";
|
|
|
|
import { describe, expect, it } from "vitest";
|
|
|
|
import { readBaselineLegacyMigration } from "./baseline-legacy-migration.test-helper";
|
|
|
|
const repoRoot = resolve(__dirname, "../../..");
|
|
const schemaPath = resolve(repoRoot, "prisma/schema/permissions.prisma");
|
|
|
|
async function readUserRoleModel() {
|
|
const schema = await readFile(schemaPath, "utf8");
|
|
const match = schema.match(/model UserRole \{(?<body>[\s\S]*?)\n\}/);
|
|
|
|
expect(match?.groups?.body, "UserRole model exists in permissions Prisma schema").toBeTruthy();
|
|
|
|
return match?.groups?.body ?? "";
|
|
}
|
|
|
|
describe("UserRole schema contract", () => {
|
|
it("documents nullable tenant assignment uniqueness as migration-managed partial indexes", async () => {
|
|
const userRoleModel = await readUserRoleModel();
|
|
|
|
expect(userRoleModel, "tenant scope remains nullable for admin roles").toMatch(/^\s*tenantId\s+String\?/m);
|
|
expect(userRoleModel, "Prisma schema documents why uniqueness is migration-managed").toContain(
|
|
"Assignment uniqueness is enforced by partial indexes in migration SQL",
|
|
);
|
|
expect(userRoleModel, "lookup index remains available for user/role/tenant reads").toMatch(
|
|
/@@index\(\[userId,\s*roleId,\s*tenantId\],\s*name:\s*"user_role_user_role_tenant_idx"\)/,
|
|
);
|
|
expect(userRoleModel, "Prisma should not declare a nullable composite unique that misses NULL admin duplicates").not.toMatch(
|
|
/@@unique\(\[userId,\s*roleId,\s*tenantId\]/,
|
|
);
|
|
});
|
|
|
|
it("adds partial unique indexes for tenant and admin assignments with duplicate preflight checks", async () => {
|
|
const migrationSql = readBaselineLegacyMigration("20260528153000_user_role_assignment_uniqueness");
|
|
|
|
expect(migrationSql, "migration rejects existing tenant-scope duplicates before indexing").toMatch(
|
|
/WHERE\s+"tenantId"\s+IS\s+NOT\s+NULL[\s\S]*GROUP\s+BY\s+"userId",\s*"roleId",\s*"tenantId"[\s\S]*HAVING\s+COUNT\(\*\)\s*>\s*1/i,
|
|
);
|
|
expect(migrationSql, "migration rejects existing admin-scope duplicates before indexing").toMatch(
|
|
/WHERE\s+"tenantId"\s+IS\s+NULL[\s\S]*GROUP\s+BY\s+"userId",\s*"roleId"[\s\S]*HAVING\s+COUNT\(\*\)\s*>\s*1/i,
|
|
);
|
|
expect(migrationSql, "tenant assignments are unique when tenantId is present").toMatch(
|
|
/CREATE\s+UNIQUE\s+INDEX\s+IF\s+NOT\s+EXISTS\s+"user_role_tenant_assignment_key"\s+ON\s+"UserRole"\s*\(\s*"userId"\s*,\s*"roleId"\s*,\s*"tenantId"\s*\)\s*WHERE\s+"tenantId"\s+IS\s+NOT\s+NULL/i,
|
|
);
|
|
expect(migrationSql, "admin assignments are unique when tenantId is null").toMatch(
|
|
/CREATE\s+UNIQUE\s+INDEX\s+IF\s+NOT\s+EXISTS\s+"user_role_admin_assignment_key"\s+ON\s+"UserRole"\s*\(\s*"userId"\s*,\s*"roleId"\s*\)\s*WHERE\s+"tenantId"\s+IS\s+NULL/i,
|
|
);
|
|
});
|
|
});
|