Skip to content

Commit feb3db5

Browse files
Improve patient_session lookup speed
- Series of EXIST statements joined with AND clauses can be repackaged as JOIN statements avoiding looping in execution
1 parent f336517 commit feb3db5

File tree

1 file changed

+47
-18
lines changed

1 file changed

+47
-18
lines changed

app/models/patient_session.rb

Lines changed: 47 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -106,28 +106,57 @@ class PatientSession < ApplicationRecord
106106

107107
scope :appear_in_programmes,
108108
->(programmes) do
109-
# Are any of the programmes administered in the session?
110-
programme_in_session =
111-
SessionProgramme
112-
.where(programme: programmes)
113-
.where("session_programmes.session_id = sessions.id")
114-
.arel
115-
.exists
109+
sessions = Session.arel_table
110+
patient_sessions = PatientSession.arel_table
111+
relevant_sessions = Arel::Table.new("relevant_sessions")
112+
session_programmes = SessionProgramme.arel_table
113+
location_programme_year_groups = LocationProgrammeYearGroup.arel_table
116114

117-
# Is the patient eligible for any of those programmes by year group?
118-
patient_in_administered_year_groups =
119-
LocationProgrammeYearGroup
120-
.where(programme: programmes)
121-
.where("location_id = sessions.location_id")
115+
relevant_sessions_query =
116+
SessionProgramme
117+
.select(
118+
:session_id,
119+
"academic_year " \
120+
"- #{Integer::AGE_CHILDREN_START_SCHOOL} " \
121+
"- year_group as birth_academic_year"
122+
)
123+
.distinct
124+
.joins(
125+
session_programmes
126+
.join(sessions)
127+
.on(session_programmes[:session_id].eq(sessions[:id]))
128+
.join_sources
129+
)
130+
.joins(
131+
sessions
132+
.join(location_programme_year_groups)
133+
.on(
134+
location_programme_year_groups[:location_id].eq(
135+
sessions[:location_id]
136+
)
137+
)
138+
.join_sources
139+
)
140+
.where(session_programmes[:programme_id].in(programmes.map(&:id)))
122141
.where(
123-
"year_group = sessions.academic_year " \
124-
"- patients.birth_academic_year " \
125-
"- #{Integer::AGE_CHILDREN_START_SCHOOL}"
142+
location_programme_year_groups[:programme_id].in(
143+
programmes.map(&:id)
144+
)
126145
)
127146
.arel
128-
.exists
129-
130-
where(programme_in_session).where(patient_in_administered_year_groups)
147+
.as("relevant_sessions")
148+
149+
joins(
150+
sessions
151+
.join(relevant_sessions_query)
152+
.on(
153+
patient_sessions[:session_id].eq(
154+
relevant_sessions[:session_id]
155+
),
156+
"relevant_sessions.birth_academic_year = patients.birth_academic_year"
157+
)
158+
.join_sources
159+
)
131160
end
132161

133162
scope :search_by_name,

0 commit comments

Comments
 (0)