Skip to content
This repository was archived by the owner on Feb 1, 2026. It is now read-only.

Commit b4f5d98

Browse files
Spacehunterzclaude
andcommitted
perf: Fix N+1 in violations.py - 4 queries to 1
Consolidated get_violation_summary() to single pass: - total count, acknowledged count, by-rule aggregation, and recent 5 all collected in one iteration instead of 4 separate queries Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 4610887 commit b4f5d98

1 file changed

Lines changed: 23 additions & 30 deletions

File tree

src/query/queries/violations.py

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -76,41 +76,34 @@ async def get_violation_summary(self, days: int = 7, timeout: int = None) -> Dic
7676
m = get_manager()
7777
async with m:
7878
async with m.connection():
79-
# Total count
8079
total = 0
81-
async for _ in Violation.select().where(Violation.violation_date >= cutoff):
82-
total += 1
83-
84-
# By rule (group by) - need to aggregate manually for async
85-
by_rule_dict = {}
86-
async for v in Violation.select().where(Violation.violation_date >= cutoff):
87-
key = (v.rule_id, v.rule_name)
88-
by_rule_dict[key] = by_rule_dict.get(key, 0) + 1
89-
90-
by_rule = [{'rule_id': k[0], 'rule_name': k[1], 'count': v}
91-
for k, v in sorted(by_rule_dict.items(), key=lambda x: -x[1])]
92-
93-
# Acknowledged count
9480
acknowledged = 0
95-
async for _ in Violation.select().where(
96-
(Violation.violation_date >= cutoff) & (Violation.acknowledged == True)
97-
):
98-
acknowledged += 1
81+
by_rule_dict = {}
82+
recent = []
83+
recent_count = 0
9984

100-
# Recent violations (last 5)
101-
recent_query = (Violation
85+
query = (Violation
10286
.select()
10387
.where(Violation.violation_date >= cutoff)
104-
.order_by(Violation.violation_date.desc())
105-
.limit(5))
106-
recent = []
107-
async for r in recent_query:
108-
recent.append({
109-
'rule_id': r.rule_id,
110-
'rule_name': r.rule_name,
111-
'description': r.description,
112-
'date': str(r.violation_date) if r.violation_date else None
113-
})
88+
.order_by(Violation.violation_date.desc()))
89+
90+
async for v in query:
91+
total += 1
92+
if v.acknowledged:
93+
acknowledged += 1
94+
key = (v.rule_id, v.rule_name)
95+
by_rule_dict[key] = by_rule_dict.get(key, 0) + 1
96+
if recent_count < 5:
97+
recent.append({
98+
'rule_id': v.rule_id,
99+
'rule_name': v.rule_name,
100+
'description': v.description,
101+
'date': str(v.violation_date) if v.violation_date else None
102+
})
103+
recent_count += 1
104+
105+
by_rule = [{'rule_id': k[0], 'rule_name': k[1], 'count': c}
106+
for k, c in sorted(by_rule_dict.items(), key=lambda x: -x[1])]
114107

115108
summary = {
116109
'total': total,

0 commit comments

Comments
 (0)