Skip to content

Commit fcee053

Browse files
Merge pull request #4638 from nhsuk/speedup_patient_lookups
Replace CTE with exists
2 parents 7da3058 + 98bc56e commit fcee053

File tree

1 file changed

+26
-33
lines changed

1 file changed

+26
-33
lines changed

app/policies/patient_policy.rb

Lines changed: 26 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -8,53 +8,46 @@ def resolve
88

99
return scope.none if team.nil?
1010

11-
patients_table = Patient.arel_table
12-
associated_patients_table = Arel::Table.new("associated_patients")
13-
14-
associated_patients = [
11+
existence_criteria = [
1512
PatientSession
16-
.select(:patient_id)
13+
.select("1")
1714
.joins(:session)
15+
.where("patient_sessions.patient_id = patients.id")
1816
.where(sessions: { team_id: team.id })
1917
.arel,
20-
ArchiveReason.select(:patient_id).where(team_id: team.id).arel,
21-
SchoolMove.select(:patient_id).where(team_id: team.id).arel,
22-
SchoolMove.select(:patient_id).where(school: team.schools).arel,
18+
ArchiveReason
19+
.select("1")
20+
.where("archive_reasons.patient_id = patients.id")
21+
.where(team_id: team.id)
22+
.arel,
23+
SchoolMove
24+
.select("1")
25+
.where("school_moves.patient_id = patients.id")
26+
.where(team_id: team.id)
27+
.arel,
28+
SchoolMove
29+
.select("1")
30+
.where("school_moves.patient_id = patients.id")
31+
.where(school: team.schools)
32+
.arel,
2333
VaccinationRecord
24-
.select(:patient_id)
34+
.select("1")
2535
.joins(:session)
36+
.where("vaccination_records.patient_id = patients.id")
2637
.where(sessions: { team_id: team.id })
2738
.arel,
2839
VaccinationRecord
29-
.select(:patient_id)
40+
.select("1")
41+
.where("vaccination_records.patient_id = patients.id")
3042
.where(performed_ods_code: organisation.ods_code, session_id: nil)
3143
.arel
3244
]
3345

34-
associated_patiens_union =
35-
Arel::Nodes::Union.new(associated_patients[0], associated_patients[1])
36-
associated_patients[2..].each do |select|
37-
associated_patiens_union =
38-
Arel::Nodes::Union.new(associated_patiens_union, select)
46+
condition = existence_criteria[0].exists
47+
existence_criteria[1..].each do |filter|
48+
condition = condition.or(filter.exists)
3949
end
40-
41-
associated_patients_query =
42-
Arel::SelectManager
43-
.new
44-
.project(Arel.star)
45-
.from(associated_patiens_union.as("t"))
46-
.group("t.patient_id")
47-
48-
join_associated_patients =
49-
patients_table
50-
.join(associated_patients_table)
51-
.on(associated_patients_table[:patient_id].eq(patients_table[:id]))
52-
.join_sources
53-
.first
54-
55-
Patient.with(associated_patients: associated_patients_query).joins(
56-
join_associated_patients
57-
)
50+
scope.where(condition)
5851
end
5952
end
6053
end

0 commit comments

Comments
 (0)