Line data Source code
1 4 : (ns matchscore.domain.match.repository.postgres
2 : (:require
3 : [honey.sql :as sql]
4 : [matchscore.domain.match.entity :as entity]
5 : [matchscore.utils.audit :as audit]
6 : [matchscore.utils.db :as utils.db]
7 : [matchscore.utils.pagination :as qh]
8 : [next.jdbc :as jdbc]))
9 :
10 :
11 4 : (defprotocol
12 : MatchPostgresRepository
13 : (find-by-id
14 : [this id]
15 : "Find match by UUID.")
16 : (find-by-series-id
17 : [this series-id]
18 : "Find all games in a series, ordered by game-number. Returns seq.")
19 : (find-by-series-ids
20 : [this series-ids]
21 : "Find all matches for multiple series in one batch query. Returns seq.")
22 : (find-by-group-id
23 : [this group-id]
24 : "Find all matches in a group. Returns seq.")
25 : (find-by-group-ids
26 : [this group-ids]
27 : "Find all matches for multiple groups in one batch query. Returns seq.")
28 : (find-by-bracket-match-id
29 : [this bracket-match-id]
30 : "Find matches for a bracket match slot. Returns seq.")
31 : (find-by-bracket-match-ids
32 : [this bracket-match-ids]
33 : "Find matches for multiple bracket matches in one batch query. Returns seq.")
34 : (search
35 : [this filters pagination]
36 : "Search. filters: {:stageId {...} :groupId {...} :bracketMatchId {...} :seriesId {...} :state {...} :eventId {...} :datetimeStart {...} :datetimeEnd {...} :participating-user-id \"uuid\"}. sort: #{:datetime-start :datetime-end :match-order}, default: :datetime-start")
37 : (save!
38 : [this match-data]
39 : "Insert a new match record. Returns [ok? result error-message].")
40 : (update-state!
41 : [this match-id state]
42 : "Update the state of a match by UUID string. Returns updated Match or nil.")
43 : (update-participants!
44 : [this match-id home-participant-id away-participant-id]
45 : "Set home and away participant IDs for a match. Returns updated Match or nil.")
46 : (update-bracket-slot-participant!
47 : [this bracket-match-id slot participant-id]
48 : "Update home (slot=1) or away (slot=2) participant for all matches of a bracket match.
49 : participant-id nil clears the field. Returns seq of updated matches."))
50 :
51 :
52 4 : (defn- -parse-datetime-filter
53 : [datetime-filter]
54 3 : (when datetime-filter
55 2 : (update-vals
56 1 : datetime-filter
57 1 : (fn [v]
58 4 : (cond (string? v)
59 1 : (try
60 5 : (java.sql.Timestamp/from (java.time.Instant/parse v))
61 0 : (catch java.time.format.DateTimeParseException _ v)
62 0 : (catch IllegalArgumentException _ v))
63 :
64 0 : (instance? java.time.Instant v) (java.sql.Timestamp/from v)
65 0 : :else v)))))
66 :
67 :
68 4 : (defn- filters->specs
69 : "Converts a GraphQL filters map to a seq of [column op value] specs."
70 : [{:keys [stageId groupId bracketMatchId seriesId state eventId datetimeStart datetimeEnd]}]
71 2 : (qh/typed-filters->specs
72 12 : {:stage-id (utils.db/cast-uuid-filter stageId)
73 3 : :group-id (utils.db/cast-uuid-filter groupId)
74 3 : :bracket-match-id (utils.db/cast-uuid-filter bracketMatchId)
75 3 : :series-id (utils.db/cast-uuid-filter seriesId)
76 1 : :state state
77 3 : :event-id (utils.db/cast-uuid-filter eventId)
78 3 : :datetime-start (-parse-datetime-filter datetimeStart)
79 3 : :datetime-end (-parse-datetime-filter datetimeEnd)}))
80 :
81 :
82 4 : (defn- participating-user-clause
83 : "Clause matching matches where the given user participates (resolved through
84 : participants.user_id). A match references its participants either directly on
85 : the matches row (home/away_participant_id) or, for bracket matches, only via
86 : bracket_match_slots — so both sources are checked."
87 : [user-id]
88 5 : (let [uid [:cast user-id :uuid]]
89 2 : [:or
90 2 : [:exists
91 6 : {:select [1]
92 4 : :from [[:participants :p]]
93 2 : :where [:and
94 4 : [:= :p.user-id uid]
95 10 : [:or [:= :p.uuid :m.home-participant-id] [:= :p.uuid :m.away-participant-id]]]}]
96 2 : [:exists
97 7 : {:select [1]
98 4 : :from [[:bracket-match-slots :bms]]
99 8 : :join [[:participants :p2] [:= :p2.uuid :bms.participant-id]]
100 10 : :where [:and [:= :bms.bracket-match-id :m.bracket-match-id] [:= :p2.user-id uid]]}]]))
101 :
102 :
103 4 : (defn- winner-belongs-to-user-clause
104 : [user-id]
105 8 : [:exists {:select [1]
106 4 : :from [[:participants :winner-participant]]
107 2 : :where [:and
108 4 : [:= :winner-participant.uuid :mr.winner-id]
109 7 : [:= :winner-participant.user-id [:cast user-id :uuid]]]}])
110 :
111 :
112 20 : (def ^:private open-match-states ["scheduled" "in_progress" "active"])
113 :
114 :
115 4 : (defn- owning-event-clause
116 : "Clause matching matches whose owning event (aliased `e`) satisfies event-condition.
117 : The event is resolved like `match-event-resolver` does — the denormalized event_id
118 : first, then the stage -> class -> event chain. Written as a subquery (not a join)
119 : so unqualified filter columns stay unambiguous."
120 : [event-condition]
121 32 : [:exists {:select [1]
122 16 : :from [[:events :e]]
123 8 : :where [:and
124 12 : [:=
125 : :e.uuid
126 12 : [:coalesce
127 : :m.event-id
128 28 : {:select [:ec.event-id]
129 16 : :from [[:stages :s]]
130 32 : :join [[:event-classes :ec] [:= :ec.uuid :s.class-id]]
131 16 : :where [:= :s.uuid :m.stage-id]}]]
132 4 : event-condition]}])
133 :
134 :
135 28 : (def ^:private event-cancelled-clause (owning-event-clause [:= :e.state "cancelled"]))
136 :
137 :
138 40 : (def ^:private regular-event-clause (owning-event-clause [:not-in :e.source ["psa" "fsu" "esf"]]))
139 :
140 :
141 4 : (def ^:private event-closed-clause
142 : "Clause matching matches whose owning event is cancelled, completed, or already over.
143 : Such a match can no longer be played, whatever its own state says: closing an event
144 : does not cascade to its matches."
145 60 : (owning-event-clause [:or [:in :e.state ["cancelled" "completed"]] [:< :e.datetime-end [:now]]]))
146 :
147 :
148 4 : (defn- count-user-outcomes
149 : [ds user-id filters]
150 4 : (let [winner-belongs-to-user (winner-belongs-to-user-clause user-id)
151 : query
152 1 : (->
153 4 : {:select
154 15 : [[[:sum [:case winner-belongs-to-user [:inline 1] :else [:inline 0]]] :won]
155 4 : [[:sum
156 3 : [:case
157 9 : [:and [:is-not :mr.winner-id nil] [:not winner-belongs-to-user]]
158 3 : [:inline 1]
159 : :else
160 3 : [:inline 0]]]
161 : :lost]
162 4 : [[:sum
163 3 : [:case
164 2 : [:and
165 4 : [:is :mr.winner-id nil]
166 4 : [:in :m.state open-match-states]
167 3 : [:not event-closed-clause]]
168 3 : [:inline 1]
169 : :else
170 3 : [:inline 0]]]
171 : :upcoming]
172 4 : [[:sum
173 3 : [:case
174 13 : [:and [:is :mr.winner-id nil] [:or [:= :m.state "cancelled"] event-cancelled-clause]]
175 3 : [:inline 1]
176 : :else
177 3 : [:inline 0]]]
178 : :cancelled]
179 4 : [[:sum
180 3 : [:case
181 10 : [:or [:is-not :mr.winner-id nil] [:= :m.state "completed"]]
182 3 : [:inline 1]
183 : :else
184 3 : [:inline 0]]]
185 : :played]]
186 4 : :from [[:matches :m]]
187 8 : :left-join [[:match-results :mr] [:= :mr.match-id :m.uuid]]}
188 5 : (qh/add-where-clause (participating-user-clause user-id))
189 11 : (cond-> (not (:include-imported? filters)) (qh/add-where-clause regular-event-clause))
190 4 : (qh/apply-filters (filters->specs filters)))
191 1 : row (->>
192 3 : (sql/format query)
193 3 : (jdbc/execute-one! ds)
194 1 : utils.db/unqualify-keys)]
195 18 : (update-vals (select-keys row [:won :lost :upcoming :cancelled :played]) #(or % 0))))
196 :
197 :
198 4 : (defn- row->match
199 : "Converts a database row to a domain Match map."
200 : [row]
201 32 : (when row (entity/make-match (utils.db/unqualify-keys row))))
202 :
203 :
204 20 : (def ^:private valid-sort-fields #{:datetime-start :datetime-end :match-order})
205 :
206 :
207 8 : (def ^:private default-sort :datetime-start)
208 :
209 :
210 4 : (def ^:private base-query
211 28 : {:select [[:m.uuid :uuid]
212 12 : [:m.home-participant-id :home-participant-id]
213 12 : [:m.away-participant-id :away-participant-id]
214 12 : [:m.event-id :event-id]
215 12 : [:m.stage-id :stage-id]
216 12 : [:m.group-id :group-id]
217 12 : [:m.bracket-match-id :bracket-match-id]
218 12 : [:m.series-id :series-id]
219 12 : [:m.game-number :game-number]
220 12 : [:m.match-order :match-order]
221 12 : [:m.state :state]
222 12 : [:m.ruleset-id :ruleset-id]
223 12 : [:m.datetime-start :datetime-start]
224 12 : [:m.datetime-end :datetime-end]
225 12 : [:m.court :court]
226 12 : [:m.extra :extra]
227 12 : [:m.created-datetime :created-datetime]
228 12 : [:m.updated-datetime :updated-datetime]
229 12 : [:m.source :source]]
230 16 : :from [[:matches :m]]})
231 :
232 :
233 4 : (defrecord
234 : PostgresMatchRepository
235 : [ds]
236 : MatchPostgresRepository
237 :
238 : (find-by-id
239 : [_ id]
240 48 : (let [query (assoc base-query :where [:= :m.uuid [:cast id :uuid]])
241 4 : result (->>
242 12 : (sql/format query)
243 12 : (jdbc/execute! ds)
244 4 : first)]
245 12 : (row->match result)))
246 :
247 : (find-by-series-id
248 : [_ series-id]
249 3 : (let [query (merge
250 1 : base-query
251 10 : {:where [:= :m.series-id [:cast series-id :uuid]]
252 4 : :order-by [[:m.game-number :asc]]})]
253 1 : (->>
254 3 : (sql/format query)
255 3 : (jdbc/execute! ds)
256 2 : (mapv row->match))))
257 :
258 : (find-by-series-ids
259 : [_ series-ids]
260 8 : (if (empty? series-ids)
261 1 : []
262 6 : (let [query (->
263 2 : base-query
264 30 : (assoc :where [:in :m.series-id (mapv #(vector :cast % :uuid) series-ids)])
265 10 : (assoc :order-by [[:m.game-number :asc]]))]
266 2 : (->>
267 6 : (sql/format query)
268 6 : (jdbc/execute! ds)
269 4 : (mapv row->match)))))
270 :
271 : (find-by-group-ids
272 : [_ group-ids]
273 16 : (if (empty? group-ids)
274 1 : []
275 12 : (let [query (->
276 4 : base-query
277 52 : (assoc :where [:in :m.group-id (mapv #(vector :cast % :uuid) group-ids)]))]
278 4 : (->>
279 12 : (sql/format query)
280 12 : (jdbc/execute! ds)
281 8 : (mapv row->match)))))
282 :
283 : (find-by-group-id
284 : [_ group-id]
285 39 : (let [query (merge base-query {:where [:= :m.group-id [:cast group-id :uuid]]})]
286 3 : (->>
287 9 : (sql/format query)
288 9 : (jdbc/execute! ds)
289 6 : (mapv row->match))))
290 :
291 : (find-by-bracket-match-id
292 : [_ bracket-match-id]
293 52 : (let [query (merge base-query {:where [:= :m.bracket-match-id [:cast bracket-match-id :uuid]]})]
294 4 : (->>
295 12 : (sql/format query)
296 12 : (jdbc/execute! ds)
297 8 : (mapv row->match))))
298 :
299 : (find-by-bracket-match-ids
300 : [_ bracket-match-ids]
301 4 : (if (empty? bracket-match-ids)
302 0 : []
303 3 : (let [query (->
304 1 : base-query
305 4 : (assoc :where [:in
306 : :m.bracket-match-id
307 9 : (mapv #(vector :cast % :uuid) bracket-match-ids)]))]
308 1 : (->>
309 3 : (sql/format query)
310 3 : (jdbc/execute! ds)
311 2 : (mapv row->match)))))
312 :
313 : (search
314 : [_ filters pagination]
315 4 : (let [participating-user-id (:participating-user-id filters)
316 3 : participating (when participating-user-id
317 3 : (participating-user-clause participating-user-id))
318 8 : base (cond-> base-query
319 10 : (and participating-user-id (not (:include-imported? filters)))
320 4 : (qh/add-where-clause regular-event-clause)
321 :
322 3 : participating (qh/add-where-clause participating))
323 3 : specs (filters->specs filters)
324 2 : query (qh/build-search-query
325 1 : base
326 1 : specs
327 1 : valid-sort-fields
328 1 : default-sort
329 1 : pagination
330 9 : {:sort-field-casts {:match-order :integer
331 : :datetime-start :timestamptz
332 : :datetime-end :timestamptz}})
333 1 : rows (->>
334 3 : (sql/format query)
335 3 : (jdbc/execute! ds)
336 2 : (mapv row->match))
337 6 : opts (when-not (:cursor pagination)
338 5 : (let [cnt-query (qh/build-count-query base specs)
339 3 : total (->>
340 3 : (sql/format cnt-query)
341 3 : (jdbc/execute-one! ds)
342 1 : utils.db/unqualify-keys
343 : :total)]
344 3 : {:total-count total}))]
345 13 : (cond-> (qh/paginate-results rows valid-sort-fields default-sort pagination opts)
346 2 : participating-user-id (assoc :outcome-counts
347 5 : (count-user-outcomes ds participating-user-id filters)))))
348 :
349 : (save!
350 : [_ match-data]
351 4 : (try
352 8 : (let [{:keys [uuid stage-id group-id bracket-match-id match-order source]} match-data
353 20 : query {:insert-into :matches
354 48 : :values [{:uuid [:cast uuid :uuid]
355 28 : :stage_id (when stage-id [:cast stage-id :uuid])
356 23 : :group_id (when group-id [:cast group-id :uuid])
357 11 : :bracket_match_id (when bracket-match-id
358 12 : [:cast bracket-match-id :uuid])
359 4 : :match_order match-order
360 20 : :source (or source "matchscore")}]
361 8 : :returning [:*]}
362 8 : result (->>
363 8 : (sql/format
364 12 : (audit/stamp query)
365 20 : {:quoted true
366 : :quoted-snake true})
367 12 : (jdbc/execute! ds)
368 4 : first
369 4 : row->match)]
370 16 : [true result nil])
371 0 : (catch Exception e [false :database-error (.getMessage e)])))
372 :
373 : (update-state!
374 : [_ match-id state]
375 21 : (let [query {:update :matches
376 9 : :set {:state state}
377 27 : :where [:= :uuid [:cast (str match-id) :uuid]]
378 6 : :returning [:*]}
379 3 : result (->>
380 15 : (sql/format (audit/stamp query))
381 9 : (jdbc/execute! ds)
382 3 : first)]
383 9 : (row->match result)))
384 :
385 : (update-participants!
386 : [_ match-id home-participant-id away-participant-id]
387 21 : (let [query {:update :matches
388 18 : :set {:home_participant_id (when home-participant-id
389 12 : [:cast home-participant-id :uuid])
390 9 : :away_participant_id (when away-participant-id
391 12 : [:cast away-participant-id :uuid])}
392 21 : :where [:= :uuid [:cast match-id :uuid]]
393 6 : :returning [:*]}
394 3 : result (->>
395 15 : (sql/format (audit/stamp query))
396 9 : (jdbc/execute! ds)
397 3 : first)]
398 9 : (row->match result)))
399 :
400 : (update-bracket-slot-participant!
401 : [_ bracket-match-id slot participant-id]
402 27 : (let [col (if (= 1 slot) :home_participant_id :away_participant_id)
403 24 : query {:update :matches
404 36 : :set {col (when participant-id [:cast participant-id :uuid])}
405 28 : :where [:= :bracket-match-id [:cast bracket-match-id :uuid]]
406 8 : :returning [:*]}]
407 4 : (->>
408 20 : (sql/format (audit/stamp query))
409 12 : (jdbc/execute! ds)
410 8 : (mapv row->match)))))
411 :
412 :
413 4 : (defn make-repository
414 : "Creates a PostgresMatchRepository from a ds."
415 : [ds]
416 12 : (->PostgresMatchRepository ds))
|