perf(db): resolve chain of command in a single recursive CTE to eliminate N+1 queries
This commit is contained in:
1 parent
2ec77677cb
commit
d0c6d1f6d0
1 file changed
+29
-21
@@ -18,27 +18,35 @@ export function buildAgentHierarchyMethods(
|
|||||||
) {
|
) {
|
||||||
return {
|
return {
|
||||||
getChainOfCommand(agentId: string): AgentRecord[] {
|
getChainOfCommand(agentId: string): AgentRecord[] {
|
||||||
const chain: AgentRecord[] = [];
|
const rows = readAll<AgentRecord & { depth: number }>(
|
||||||
const visited = new Set<string>();
|
`WITH RECURSIVE chain AS (
|
||||||
let current: AgentRecord | undefined;
|
SELECT id, company_id as companyId, name, role, title, department, status,
|
||||||
try {
|
reports_to as reportsTo, connector_id as connectorId, workspace_id as workspaceId,
|
||||||
current = deps.getAgent(agentId);
|
model, capabilities, budget_monthly_usd as budgetMonthlyUsd,
|
||||||
} catch {
|
spent_monthly_usd as spentMonthlyUsd, metadata_json as metadataJson,
|
||||||
return chain;
|
heartbeat_enabled as heartbeatEnabled, heartbeat_interval_sec as heartbeatIntervalSec,
|
||||||
}
|
last_heartbeat_at as lastHeartbeatAt, created_at as createdAt, updated_at as updatedAt,
|
||||||
while (current?.reportsTo) {
|
0 as depth
|
||||||
if (visited.has(current.reportsTo)) {
|
FROM agents WHERE id = ?
|
||||||
break;
|
UNION ALL
|
||||||
}
|
SELECT a.id, a.company_id, a.name, a.role, a.title, a.department, a.status,
|
||||||
visited.add(current.reportsTo);
|
a.reports_to, a.connector_id, a.workspace_id,
|
||||||
try {
|
a.model, a.capabilities, a.budget_monthly_usd,
|
||||||
current = deps.getAgent(current.reportsTo);
|
a.spent_monthly_usd, a.metadata_json,
|
||||||
chain.push(current);
|
a.heartbeat_enabled, a.heartbeat_interval_sec,
|
||||||
} catch {
|
a.last_heartbeat_at, a.created_at, a.updated_at,
|
||||||
break;
|
c.depth + 1
|
||||||
}
|
FROM agents a JOIN chain c ON a.id = c.reportsTo
|
||||||
}
|
WHERE c.depth < 20
|
||||||
return chain;
|
)
|
||||||
|
SELECT * FROM chain ORDER BY depth`,
|
||||||
|
agentId,
|
||||||
|
);
|
||||||
|
// Skip self (depth 0); return ancestors from direct manager upward.
|
||||||
|
return rows.slice(1).map((record) => ({
|
||||||
|
...record,
|
||||||
|
heartbeatEnabled: toBoolean(record.heartbeatEnabled),
|
||||||
|
})) as AgentRecord[];
|
||||||
},
|
},
|
||||||
|
|
||||||
getDirectReports(agentId: string, companyId: string): AgentRecord[] {
|
getDirectReports(agentId: string, companyId: string): AgentRecord[] {
|
||||||
|
|||||||
Reference in new issue
Block a user