Spaces:
Runtime error
Runtime error
Greg Claude Opus 4.7 (1M context) commited on
Commit ·
db14bae
1
Parent(s): 7d5d51b
perf(section-subjects): eliminate N+1 in GET and PUT /section-subjects
Browse filesBatch-load all subjects in a single query for the GET list. For the
PUT, replace per-subject validation loop with a single batch query
to fetch valid subject IDs, then filter on that set.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
backend/app/api/v1/endpoints/section_subjects.py
CHANGED
|
@@ -26,9 +26,12 @@ def list_section_subjects(
|
|
| 26 |
if section_id:
|
| 27 |
query = query.filter(SectionSubject.section_id == section_id)
|
| 28 |
items = query.all()
|
|
|
|
|
|
|
|
|
|
| 29 |
result = []
|
| 30 |
for ss in items:
|
| 31 |
-
sub =
|
| 32 |
result.append(SectionSubjectsResponse(
|
| 33 |
section_id=ss.section_id,
|
| 34 |
subject_id=ss.subject_id,
|
|
@@ -49,12 +52,14 @@ def set_section_subjects(
|
|
| 49 |
).first()
|
| 50 |
if not sec:
|
| 51 |
raise HTTPException(status_code=404, detail="Section not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
db.query(SectionSubject).filter(SectionSubject.section_id == section_id).delete()
|
| 53 |
for sid in subject_ids:
|
| 54 |
-
|
| 55 |
-
Subject.id == sid, Subject.account_id == current_user.account_id
|
| 56 |
-
).first()
|
| 57 |
-
if sub:
|
| 58 |
db.add(SectionSubject(
|
| 59 |
section_id=section_id, subject_id=sid,
|
| 60 |
account_id=current_user.account_id
|
|
|
|
| 26 |
if section_id:
|
| 27 |
query = query.filter(SectionSubject.section_id == section_id)
|
| 28 |
items = query.all()
|
| 29 |
+
# Batch-load subjects referenced by all items
|
| 30 |
+
subject_ids = {ss.subject_id for ss in items if ss.subject_id is not None}
|
| 31 |
+
subjects_by_id = {s.id: s for s in db.query(Subject).filter(Subject.id.in_(subject_ids)).all()} if subject_ids else {}
|
| 32 |
result = []
|
| 33 |
for ss in items:
|
| 34 |
+
sub = subjects_by_id.get(ss.subject_id)
|
| 35 |
result.append(SectionSubjectsResponse(
|
| 36 |
section_id=ss.section_id,
|
| 37 |
subject_id=ss.subject_id,
|
|
|
|
| 52 |
).first()
|
| 53 |
if not sec:
|
| 54 |
raise HTTPException(status_code=404, detail="Section not found")
|
| 55 |
+
# Batch-validate subjects belong to the account (single query)
|
| 56 |
+
valid_subject_ids = {s.id for s in db.query(Subject).filter(
|
| 57 |
+
Subject.id.in_(subject_ids),
|
| 58 |
+
Subject.account_id == current_user.account_id,
|
| 59 |
+
).all()} if subject_ids else set()
|
| 60 |
db.query(SectionSubject).filter(SectionSubject.section_id == section_id).delete()
|
| 61 |
for sid in subject_ids:
|
| 62 |
+
if sid in valid_subject_ids:
|
|
|
|
|
|
|
|
|
|
| 63 |
db.add(SectionSubject(
|
| 64 |
section_id=section_id, subject_id=sid,
|
| 65 |
account_id=current_user.account_id
|