perf(db): add missing indexes, fix N+1 batch delete, add pagination limits
- Add indexes on Resource(blueprintId, roleId), DemandRequirement(roleId),
Assignment(roleId) — commonly filtered FK columns that were missing indexes
- Replace N+1 batch delete pattern (2N queries) with findAllocationEntries()
that does 2 total queries via findMany({ id: { in: ids } })
- Add take/skip pagination with default limit of 500 to listDemands and
listAssignments to prevent unbounded result sets
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,7 @@ import {
|
||||
createDemandRequirement,
|
||||
deleteAllocationEntry,
|
||||
deleteAssignment,
|
||||
findAllocationEntries,
|
||||
loadAllocationEntry,
|
||||
updateAllocationEntry,
|
||||
updateAssignment,
|
||||
@@ -68,21 +69,18 @@ export async function createAllocationReadModelEntry(
|
||||
}).allocations[0]!;
|
||||
}
|
||||
|
||||
const assignment = await createAssignment(
|
||||
tx,
|
||||
{
|
||||
resourceId: input.resourceId,
|
||||
projectId: input.projectId,
|
||||
startDate: input.startDate,
|
||||
endDate: input.endDate,
|
||||
hoursPerDay: input.hoursPerDay,
|
||||
percentage: input.percentage,
|
||||
role: input.role,
|
||||
roleId: input.roleId,
|
||||
status: input.status,
|
||||
metadata: input.metadata,
|
||||
},
|
||||
);
|
||||
const assignment = await createAssignment(tx, {
|
||||
resourceId: input.resourceId,
|
||||
projectId: input.projectId,
|
||||
startDate: input.startDate,
|
||||
endDate: input.endDate,
|
||||
hoursPerDay: input.hoursPerDay,
|
||||
percentage: input.percentage,
|
||||
role: input.role,
|
||||
roleId: input.roleId,
|
||||
status: input.status,
|
||||
metadata: input.metadata,
|
||||
});
|
||||
|
||||
return buildSplitAllocationReadModel({
|
||||
demandRequirements: [],
|
||||
@@ -94,17 +92,20 @@ export async function ensureAssignmentRecord(
|
||||
db: Pick<PrismaClient, "$transaction" | "assignment" | "resource">,
|
||||
input: EnsureAssignmentInput,
|
||||
) {
|
||||
const existing = (await db.assignment.findMany({
|
||||
where: {
|
||||
resourceId: input.resourceId,
|
||||
projectId: input.projectId,
|
||||
},
|
||||
include: ASSIGNMENT_INCLUDE,
|
||||
orderBy: { startDate: "asc" },
|
||||
})).find((assignment) => (
|
||||
toIsoDate(assignment.startDate) === toIsoDate(input.startDate)
|
||||
&& toIsoDate(assignment.endDate) === toIsoDate(input.endDate)
|
||||
));
|
||||
const existing = (
|
||||
await db.assignment.findMany({
|
||||
where: {
|
||||
resourceId: input.resourceId,
|
||||
projectId: input.projectId,
|
||||
},
|
||||
include: ASSIGNMENT_INCLUDE,
|
||||
orderBy: { startDate: "asc" },
|
||||
})
|
||||
).find(
|
||||
(assignment) =>
|
||||
toIsoDate(assignment.startDate) === toIsoDate(input.startDate) &&
|
||||
toIsoDate(assignment.endDate) === toIsoDate(input.endDate),
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
if (existing.status !== AllocationStatus.CANCELLED) {
|
||||
@@ -122,24 +123,21 @@ export async function ensureAssignmentRecord(
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
|
||||
}
|
||||
|
||||
const updated = await db.$transaction(async (tx) => updateAssignment(
|
||||
tx as Parameters<typeof updateAssignment>[0],
|
||||
existing.id,
|
||||
{
|
||||
const updated = await db.$transaction(async (tx) =>
|
||||
updateAssignment(tx as Parameters<typeof updateAssignment>[0], existing.id, {
|
||||
status: AllocationStatus.PROPOSED,
|
||||
hoursPerDay: input.hoursPerDay,
|
||||
percentage: (input.hoursPerDay / 8) * 100,
|
||||
dailyCostCents: Math.round(resource.lcrCents * input.hoursPerDay),
|
||||
...(input.role ? { role: input.role } : {}),
|
||||
},
|
||||
));
|
||||
}),
|
||||
);
|
||||
|
||||
return { assignment: updated, action: "reactivated" as const };
|
||||
}
|
||||
|
||||
const assignment = await db.$transaction(async (tx) => createAssignment(
|
||||
tx as Parameters<typeof createAssignment>[0],
|
||||
{
|
||||
const assignment = await db.$transaction(async (tx) =>
|
||||
createAssignment(tx as Parameters<typeof createAssignment>[0], {
|
||||
resourceId: input.resourceId,
|
||||
projectId: input.projectId,
|
||||
startDate: input.startDate,
|
||||
@@ -149,8 +147,8 @@ export async function ensureAssignmentRecord(
|
||||
status: AllocationStatus.PROPOSED,
|
||||
metadata: {},
|
||||
...(input.role ? { role: input.role } : {}),
|
||||
},
|
||||
));
|
||||
}),
|
||||
);
|
||||
|
||||
return { assignment, action: "created" as const };
|
||||
}
|
||||
@@ -168,8 +166,7 @@ export async function updateAllocationWithAudit(
|
||||
id,
|
||||
demandRequirementUpdate:
|
||||
existing.kind === "assignment" ? {} : toDemandRequirementUpdateInput(data),
|
||||
assignmentUpdate:
|
||||
existing.kind === "demand" ? {} : toAssignmentUpdateInput(data),
|
||||
assignmentUpdate: existing.kind === "demand" ? {} : toAssignmentUpdateInput(data),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -191,10 +188,7 @@ export async function updateAllocationWithAudit(
|
||||
return { existing, updated };
|
||||
}
|
||||
|
||||
export async function deleteAssignmentWithAudit(
|
||||
db: AllocationMutationDb,
|
||||
id: string,
|
||||
) {
|
||||
export async function deleteAssignmentWithAudit(db: AllocationMutationDb, id: string) {
|
||||
const existing = await findUniqueOrThrow(
|
||||
db.assignment.findUnique({
|
||||
where: { id },
|
||||
@@ -204,10 +198,7 @@ export async function deleteAssignmentWithAudit(
|
||||
);
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await deleteAssignment(
|
||||
tx as Parameters<typeof deleteAssignment>[0],
|
||||
id,
|
||||
);
|
||||
await deleteAssignment(tx as Parameters<typeof deleteAssignment>[0], id);
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
@@ -222,24 +213,20 @@ export async function deleteAssignmentWithAudit(
|
||||
return existing;
|
||||
}
|
||||
|
||||
export async function deleteAllocationWithAudit(
|
||||
db: AllocationMutationDb,
|
||||
id: string,
|
||||
) {
|
||||
export async function deleteAllocationWithAudit(db: AllocationMutationDb, id: string) {
|
||||
const existing = await loadAllocationEntry(db, id);
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await deleteAllocationEntry(
|
||||
tx as Parameters<typeof deleteAllocationEntry>[0],
|
||||
existing,
|
||||
);
|
||||
await deleteAllocationEntry(tx as Parameters<typeof deleteAllocationEntry>[0], existing);
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
entityType: "Allocation",
|
||||
entityId: id,
|
||||
action: "DELETE",
|
||||
changes: { before: existing.entry } as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
||||
changes: {
|
||||
before: existing.entry,
|
||||
} as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -247,20 +234,13 @@ export async function deleteAllocationWithAudit(
|
||||
return existing;
|
||||
}
|
||||
|
||||
export async function batchDeleteAllocationsWithAudit(
|
||||
db: AllocationMutationDb,
|
||||
ids: string[],
|
||||
) {
|
||||
const existing = (
|
||||
await Promise.all(ids.map(async (id) => findAllocationEntryOrNull(db, id)))
|
||||
).filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));
|
||||
export async function batchDeleteAllocationsWithAudit(db: AllocationMutationDb, ids: string[]) {
|
||||
// Batch-load in 2 queries (demand + assignment) instead of 2N individual lookups
|
||||
const existing = await findAllocationEntries(db, ids);
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
for (const allocation of existing) {
|
||||
await deleteAllocationEntry(
|
||||
tx as Parameters<typeof deleteAllocationEntry>[0],
|
||||
allocation,
|
||||
);
|
||||
await deleteAllocationEntry(tx as Parameters<typeof deleteAllocationEntry>[0], allocation);
|
||||
}
|
||||
|
||||
await tx.auditLog.create({
|
||||
@@ -290,16 +270,16 @@ export async function batchUpdateAllocationStatusWithAudit(
|
||||
) {
|
||||
const updated = await db.$transaction(async (tx) => {
|
||||
const updatedAllocations = await Promise.all(
|
||||
input.ids.map(async (id) => (
|
||||
await updateAllocationEntry(
|
||||
tx as Parameters<typeof updateAllocationEntry>[0],
|
||||
{
|
||||
id,
|
||||
demandRequirementUpdate: { status: input.status },
|
||||
assignmentUpdate: { status: input.status },
|
||||
},
|
||||
)
|
||||
).allocation),
|
||||
input.ids.map(
|
||||
async (id) =>
|
||||
(
|
||||
await updateAllocationEntry(tx as Parameters<typeof updateAllocationEntry>[0], {
|
||||
id,
|
||||
demandRequirementUpdate: { status: input.status },
|
||||
assignmentUpdate: { status: input.status },
|
||||
})
|
||||
).allocation,
|
||||
),
|
||||
);
|
||||
|
||||
await tx.auditLog.create({
|
||||
|
||||
@@ -5,7 +5,11 @@ import { anonymizeResource, getAnonymizationDirectory } from "../../lib/anonymiz
|
||||
import { planningReadProcedure } from "../../trpc.js";
|
||||
import { buildResourceAvailabilitySummary, buildResourceAvailabilityView } from "./availability.js";
|
||||
import { ASSIGNMENT_INCLUDE, DEMAND_INCLUDE } from "./shared.js";
|
||||
import { getDemandRequirementByIdOrThrow, loadAllocationReadModel, resolveAssignmentBySelection } from "./support.js";
|
||||
import {
|
||||
getDemandRequirementByIdOrThrow,
|
||||
loadAllocationReadModel,
|
||||
resolveAssignmentBySelection,
|
||||
} from "./support.js";
|
||||
|
||||
export const allocationReadProcedures = {
|
||||
list: planningReadProcedure
|
||||
@@ -37,6 +41,8 @@ export const allocationReadProcedures = {
|
||||
projectId: z.string().optional(),
|
||||
status: z.nativeEnum(AllocationStatus).optional(),
|
||||
roleId: z.string().optional(),
|
||||
take: z.number().int().min(1).max(1000).default(500),
|
||||
skip: z.number().int().min(0).default(0),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
@@ -48,6 +54,8 @@ export const allocationReadProcedures = {
|
||||
},
|
||||
include: DEMAND_INCLUDE,
|
||||
orderBy: { startDate: "asc" },
|
||||
take: input.take,
|
||||
skip: input.skip,
|
||||
});
|
||||
const directory = await getAnonymizationDirectory(ctx.db);
|
||||
if (!directory) {
|
||||
@@ -55,11 +63,11 @@ export const allocationReadProcedures = {
|
||||
}
|
||||
return demands.map((demand) => ({
|
||||
...demand,
|
||||
assignments: demand.assignments.map((assignment) => (
|
||||
assignments: demand.assignments.map((assignment) =>
|
||||
assignment.resource
|
||||
? { ...assignment, resource: anonymizeResource(assignment.resource, directory) }
|
||||
: assignment
|
||||
)),
|
||||
: assignment,
|
||||
),
|
||||
}));
|
||||
}),
|
||||
|
||||
@@ -70,6 +78,8 @@ export const allocationReadProcedures = {
|
||||
resourceId: z.string().optional(),
|
||||
status: z.nativeEnum(AllocationStatus).optional(),
|
||||
demandRequirementId: z.string().optional(),
|
||||
take: z.number().int().min(1).max(1000).default(500),
|
||||
skip: z.number().int().min(0).default(0),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
@@ -82,16 +92,18 @@ export const allocationReadProcedures = {
|
||||
},
|
||||
include: ASSIGNMENT_INCLUDE,
|
||||
orderBy: { startDate: "asc" },
|
||||
take: input.take,
|
||||
skip: input.skip,
|
||||
});
|
||||
const directory = await getAnonymizationDirectory(ctx.db);
|
||||
if (!directory) {
|
||||
return assignments;
|
||||
}
|
||||
return assignments.map((assignment) => (
|
||||
return assignments.map((assignment) =>
|
||||
assignment.resource
|
||||
? { ...assignment, resource: anonymizeResource(assignment.resource, directory) }
|
||||
: assignment
|
||||
));
|
||||
: assignment,
|
||||
);
|
||||
}),
|
||||
|
||||
getAssignmentById: planningReadProcedure
|
||||
@@ -115,15 +127,17 @@ export const allocationReadProcedures = {
|
||||
}),
|
||||
|
||||
resolveAssignment: planningReadProcedure
|
||||
.input(z.object({
|
||||
assignmentId: z.string().optional(),
|
||||
resourceId: z.string().optional(),
|
||||
projectId: z.string().optional(),
|
||||
startDate: z.coerce.date().optional(),
|
||||
endDate: z.coerce.date().optional(),
|
||||
selectionMode: z.enum(["WINDOW", "EXACT_START"]).default("EXACT_START"),
|
||||
excludeCancelled: z.boolean().default(false),
|
||||
}))
|
||||
.input(
|
||||
z.object({
|
||||
assignmentId: z.string().optional(),
|
||||
resourceId: z.string().optional(),
|
||||
projectId: z.string().optional(),
|
||||
startDate: z.coerce.date().optional(),
|
||||
endDate: z.coerce.date().optional(),
|
||||
selectionMode: z.enum(["WINDOW", "EXACT_START"]).default("EXACT_START"),
|
||||
excludeCancelled: z.boolean().default(false),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => resolveAssignmentBySelection(ctx.db, input)),
|
||||
|
||||
getDemandRequirementById: planningReadProcedure
|
||||
@@ -131,33 +145,42 @@ export const allocationReadProcedures = {
|
||||
.query(async ({ ctx, input }) => getDemandRequirementByIdOrThrow(ctx.db, input.id)),
|
||||
|
||||
checkResourceAvailability: planningReadProcedure
|
||||
.input(z.object({
|
||||
resourceId: z.string(),
|
||||
startDate: z.coerce.date(),
|
||||
endDate: z.coerce.date(),
|
||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||
}))
|
||||
.input(
|
||||
z.object({
|
||||
resourceId: z.string(),
|
||||
startDate: z.coerce.date(),
|
||||
endDate: z.coerce.date(),
|
||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { vacations: _vacations, ...availability } = await buildResourceAvailabilityView(ctx.db, input);
|
||||
const { vacations: _vacations, ...availability } = await buildResourceAvailabilityView(
|
||||
ctx.db,
|
||||
input,
|
||||
);
|
||||
return availability;
|
||||
}),
|
||||
|
||||
getResourceAvailabilityView: planningReadProcedure
|
||||
.input(z.object({
|
||||
resourceId: z.string(),
|
||||
startDate: z.coerce.date(),
|
||||
endDate: z.coerce.date(),
|
||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||
}))
|
||||
.input(
|
||||
z.object({
|
||||
resourceId: z.string(),
|
||||
startDate: z.coerce.date(),
|
||||
endDate: z.coerce.date(),
|
||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => buildResourceAvailabilityView(ctx.db, input)),
|
||||
|
||||
getResourceAvailabilitySummary: planningReadProcedure
|
||||
.input(z.object({
|
||||
resourceId: z.string(),
|
||||
startDate: z.coerce.date(),
|
||||
endDate: z.coerce.date(),
|
||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||
}))
|
||||
.input(
|
||||
z.object({
|
||||
resourceId: z.string(),
|
||||
startDate: z.coerce.date(),
|
||||
endDate: z.coerce.date(),
|
||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const availability = await buildResourceAvailabilityView(ctx.db, input);
|
||||
return buildResourceAvailabilitySummary(availability, input);
|
||||
|
||||
Reference in New Issue
Block a user