Greg Claude Opus 4.7 (1M context) commited on
Commit
bc019a7
·
1 Parent(s): bbd61b0

perf(teacher): eliminate N+1 in /subjects, /sections, /schedule

Browse files

Batch-load Subject, Section, and Enrollment counts before the
assignment loop in /subjects and /sections. Inline _section_subjects
helper with pre-fetched SectionSubject rows grouped by section_id.
Batch-load Section+Subject before the schedule loop in /schedule.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

backend/app/api/v1/endpoints/teacher.py CHANGED
@@ -1,6 +1,6 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status, Query
2
  from fastapi.responses import StreamingResponse
3
- from sqlalchemy import or_, and_
4
  from sqlalchemy.orm import Session
5
  from datetime import date, datetime, time, timedelta
6
  from typing import Optional
@@ -135,18 +135,30 @@ def teacher_subjects(
135
  TeacherSection.account_id == current_user.account_id,
136
  ).all()
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  seen_subjects: dict[int, dict] = {}
139
  for a in assignments:
140
- subj = db.query(Subject).filter(Subject.id == a.subject_id).first()
141
  if not subj:
142
  continue
143
- sec = db.query(Section).filter(Section.id == a.section_id).first()
144
  if not sec:
145
  continue
146
- count = db.query(Enrollment).filter(
147
- Enrollment.section_id == sec.id,
148
- Enrollment.account_id == current_user.account_id,
149
- ).count()
150
  if subj.id not in seen_subjects:
151
  seen_subjects[subj.id] = {
152
  "id": subj.id, "name": subj.name, "code": subj.code,
@@ -314,29 +326,56 @@ def teacher_sections(
314
  ):
315
  result = []
316
 
317
- def _section_subjects(section_id: int, db: Session):
318
- """Get all subjects linked to a section via SectionSubject."""
319
- ssl = db.query(SectionSubject).filter(SectionSubject.section_id == section_id).all()
320
- refs = []
321
- for ss in ssl:
322
- sub = db.query(Subject).filter(Subject.id == ss.subject_id).first()
323
- refs.append(SubjectRef(subject_id=ss.subject_id, subject_name=sub.name if sub else None))
324
- return refs
325
-
326
  assignments = db.query(TeacherSection).filter(
327
  TeacherSection.teacher_id == current_user.id,
328
  TeacherSection.account_id == current_user.account_id,
329
  ).all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  for ta in assignments:
331
- sec = db.query(Section).filter(Section.id == ta.section_id).first()
332
  if not sec:
333
  continue
334
- subj = db.query(Subject).filter(Subject.id == ta.subject_id).first()
335
- subjects = _section_subjects(sec.id, db)
336
- count = db.query(Enrollment).filter(
337
- Enrollment.section_id == sec.id,
338
- Enrollment.account_id == current_user.account_id,
339
- ).count()
 
 
 
 
340
  result.append(TeacherSectionResponse(
341
  id=sec.id, name=sec.name, subject_id=ta.subject_id, subject_name=subj.name if subj else None,
342
  subjects=subjects,
@@ -711,10 +750,16 @@ def teacher_schedule(
711
  SectionSchedule.account_id == current_user.account_id,
712
  ).order_by(SectionSchedule.day_of_week, SectionSchedule.entry_time).all()
713
 
 
 
 
 
 
 
714
  today_dow = date.today().weekday()
715
  for s in all_schedules:
716
- sec = db.query(Section).filter(Section.id == s.section_id).first()
717
- sub = db.query(Subject).filter(Subject.id == s.subject_id).first() if s.subject_id else None
718
  block = ScheduleBlock(
719
  id=s.id,
720
  section_id=s.section_id,
 
1
  from fastapi import APIRouter, Depends, HTTPException, status, Query
2
  from fastapi.responses import StreamingResponse
3
+ from sqlalchemy import or_, and_, func
4
  from sqlalchemy.orm import Session
5
  from datetime import date, datetime, time, timedelta
6
  from typing import Optional
 
135
  TeacherSection.account_id == current_user.account_id,
136
  ).all()
137
 
138
+ # Batch-load subjects, sections, and enrollment counts
139
+ subject_ids = {a.subject_id for a in assignments if a.subject_id is not None}
140
+ section_ids = {a.section_id for a in assignments if a.section_id is not None}
141
+ subjects_by_id = {s.id: s for s in db.query(Subject).filter(Subject.id.in_(subject_ids)).all()} if subject_ids else {}
142
+ sections_by_id = {s.id: s for s in db.query(Section).filter(Section.id.in_(section_ids)).all()} if section_ids else {}
143
+ enrollment_counts_by_section = dict(
144
+ db.query(Enrollment.section_id, func.count(Enrollment.id))
145
+ .filter(
146
+ Enrollment.section_id.in_(section_ids),
147
+ Enrollment.account_id == current_user.account_id,
148
+ )
149
+ .group_by(Enrollment.section_id)
150
+ .all()
151
+ ) if section_ids else {}
152
+
153
  seen_subjects: dict[int, dict] = {}
154
  for a in assignments:
155
+ subj = subjects_by_id.get(a.subject_id)
156
  if not subj:
157
  continue
158
+ sec = sections_by_id.get(a.section_id)
159
  if not sec:
160
  continue
161
+ count = enrollment_counts_by_section.get(sec.id, 0)
 
 
 
162
  if subj.id not in seen_subjects:
163
  seen_subjects[subj.id] = {
164
  "id": subj.id, "name": subj.name, "code": subj.code,
 
326
  ):
327
  result = []
328
 
 
 
 
 
 
 
 
 
 
329
  assignments = db.query(TeacherSection).filter(
330
  TeacherSection.teacher_id == current_user.id,
331
  TeacherSection.account_id == current_user.account_id,
332
  ).all()
333
+
334
+ # Batch-load all related data upfront
335
+ sec_ids = {ta.section_id for ta in assignments if ta.section_id is not None}
336
+ subj_ids = {ta.subject_id for ta in assignments if ta.subject_id is not None}
337
+ sections_by_id = {s.id: s for s in db.query(Section).filter(Section.id.in_(sec_ids)).all()} if sec_ids else {}
338
+ subjects_by_id = {s.id: s for s in db.query(Subject).filter(Subject.id.in_(subj_ids)).all()} if subj_ids else {}
339
+
340
+ # Batch-load SectionSubject rows and the subjects they reference
341
+ sec_subject_rows = db.query(SectionSubject).filter(SectionSubject.section_id.in_(sec_ids)).all() if sec_ids else []
342
+ ss_subject_ids = {ss.subject_id for ss in sec_subject_rows if ss.subject_id is not None}
343
+ # Merge with already-fetched subjects dict (may overlap)
344
+ extra_subjects = {s.id: s for s in db.query(Subject).filter(
345
+ Subject.id.in_(ss_subject_ids - subjects_by_id.keys())
346
+ ).all()} if (ss_subject_ids - subjects_by_id.keys()) else {}
347
+ all_subjects_by_id = {**subjects_by_id, **extra_subjects}
348
+
349
+ # Group SectionSubject rows by section_id
350
+ sec_subjects_by_section: dict[int, list] = {}
351
+ for ss in sec_subject_rows:
352
+ sec_subjects_by_section.setdefault(ss.section_id, []).append(ss)
353
+
354
+ # Batch enrollment counts per section
355
+ enrollment_counts_by_section = dict(
356
+ db.query(Enrollment.section_id, func.count(Enrollment.id))
357
+ .filter(
358
+ Enrollment.section_id.in_(sec_ids),
359
+ Enrollment.account_id == current_user.account_id,
360
+ )
361
+ .group_by(Enrollment.section_id)
362
+ .all()
363
+ ) if sec_ids else {}
364
+
365
  for ta in assignments:
366
+ sec = sections_by_id.get(ta.section_id)
367
  if not sec:
368
  continue
369
+ subj = subjects_by_id.get(ta.subject_id)
370
+ # Build subject refs from pre-fetched SectionSubject rows
371
+ subjects = [
372
+ SubjectRef(
373
+ subject_id=ss.subject_id,
374
+ subject_name=all_subjects_by_id[ss.subject_id].name if ss.subject_id in all_subjects_by_id else None,
375
+ )
376
+ for ss in sec_subjects_by_section.get(sec.id, [])
377
+ ]
378
+ count = enrollment_counts_by_section.get(sec.id, 0)
379
  result.append(TeacherSectionResponse(
380
  id=sec.id, name=sec.name, subject_id=ta.subject_id, subject_name=subj.name if subj else None,
381
  subjects=subjects,
 
750
  SectionSchedule.account_id == current_user.account_id,
751
  ).order_by(SectionSchedule.day_of_week, SectionSchedule.entry_time).all()
752
 
753
+ # Batch-load sections and subjects referenced by schedules
754
+ sched_section_ids = {s.section_id for s in all_schedules if s.section_id is not None}
755
+ sched_subject_ids = {s.subject_id for s in all_schedules if s.subject_id is not None}
756
+ sched_sections_by_id = {s.id: s for s in db.query(Section).filter(Section.id.in_(sched_section_ids)).all()} if sched_section_ids else {}
757
+ sched_subjects_by_id = {s.id: s for s in db.query(Subject).filter(Subject.id.in_(sched_subject_ids)).all()} if sched_subject_ids else {}
758
+
759
  today_dow = date.today().weekday()
760
  for s in all_schedules:
761
+ sec = sched_sections_by_id.get(s.section_id)
762
+ sub = sched_subjects_by_id.get(s.subject_id) if s.subject_id else None
763
  block = ScheduleBlock(
764
  id=s.id,
765
  section_id=s.section_id,