Line data Source code
1 4 : (ns matchscore.domain.match-result.repository.postgres
2 : (:require
3 : [cats.monad.either :as either]
4 : [cheshire.core :as json]
5 : [honey.sql :as sql]
6 : [matchscore.domain.match-result.entity :as entity]
7 : [matchscore.utils.audit :as audit]
8 : [matchscore.utils.db :as utils.db]
9 : [matchscore.utils.errors :as utils.errors]
10 : [matchscore.utils.pagination :as qh]
11 : [next.jdbc :as jdbc]))
12 :
13 :
14 4 : (defprotocol
15 : MatchResultPostgresRepository
16 : (find-by-id
17 : [this id]
18 : "Find match result by UUID.")
19 : (find-by-match-id
20 : [this match-id]
21 : "Find result for a match (one-to-one). Returns single record or nil.")
22 : (find-by-match-ids
23 : [this match-ids]
24 : "Find results for multiple matches in one batch query. Returns seq.")
25 : (find-by-bracket-match-ids
26 : [this bracket-match-ids]
27 : "Find results for multiple bracket matches via direct matches or series+match join. Returns a seq of raw maps (not MatchResult entities), including :bracket-match-id for grouping.")
28 : (search
29 : [this filters pagination]
30 : "Search. filters: {:matchId {...} :outcome {...}}. sort: #{:created-datetime}, default: :created-datetime")
31 : (save!
32 : [this match-result]
33 : "Upsert a match result (insert or update on conflict match_id). Returns Either<Error, MatchResult>.")
34 : (delete-by-match-id!
35 : [this match-id]
36 : "Delete the match result for a given match UUID string. Returns execute result."))
37 :
38 :
39 4 : (defn- filters->specs
40 : "Converts a GraphQL filters map to a seq of [column op value] specs."
41 : [{:keys [matchId outcome]}]
42 2 : (qh/typed-filters->specs
43 6 : {:match-id (utils.db/cast-uuid-filter matchId)
44 1 : :outcome outcome}))
45 :
46 :
47 4 : (defn- row->match-result
48 : "Converts a database row to a domain MatchResult map."
49 : [row]
50 32 : (when row (entity/make-match-result (utils.db/unqualify-keys row))))
51 :
52 :
53 12 : (def ^:private valid-sort-fields #{:created-datetime})
54 :
55 :
56 8 : (def ^:private default-sort :created-datetime)
57 :
58 :
59 4 : (defn- match-result->row
60 : "Converts a domain MatchResult map to a database row for upsert."
61 : [{:keys [uuid match-id winner-id loser-id ended-at outcome home-score away-score extra source]}]
62 15 : (cond->
63 28 : {:uuid [:cast (str uuid) :uuid]
64 12 : :match_id [:cast (str match-id) :uuid]
65 2 : :outcome outcome
66 2 : :home_score home-score
67 2 : :away_score away-score
68 2 : :ended_at ended-at
69 10 : :source (or source "matchscore")}
70 20 : winner-id (assoc :winner_id [:cast (str winner-id) :uuid])
71 2 : loser-id (assoc :loser_id [:cast (str loser-id) :uuid])
72 2 : extra (assoc :extra [:cast (json/generate-string extra) :jsonb])))
73 :
74 :
75 4 : (def ^:private base-query
76 28 : {:select [[:mr.uuid :uuid]
77 12 : [:mr.match-id :match-id]
78 12 : [:mr.winner-id :winner-id]
79 12 : [:mr.loser-id :loser-id]
80 12 : [:mr.ended-at :ended-at]
81 12 : [:mr.outcome :outcome]
82 12 : [:mr.home-score :home-score]
83 12 : [:mr.away-score :away-score]
84 12 : [:mr.extra :extra]
85 12 : [:mr.created-datetime :created-datetime]
86 12 : [:mr.source :source]]
87 16 : :from [[:match-results :mr]]})
88 :
89 :
90 4 : (defrecord
91 : PostgresMatchResultRepository
92 : [ds]
93 : MatchResultPostgresRepository
94 :
95 : (find-by-id
96 : [_ id]
97 12 : (let [query (assoc base-query :where [:= :mr.uuid [:cast id :uuid]])
98 1 : result (->>
99 3 : (sql/format query)
100 3 : (jdbc/execute! ds)
101 1 : first)]
102 3 : (row->match-result result)))
103 :
104 : (find-by-match-id
105 : [_ match-id]
106 24 : (let [query (assoc base-query :where [:= :mr.match-id [:cast match-id :uuid]])
107 2 : result (->>
108 6 : (sql/format query)
109 6 : (jdbc/execute! ds)
110 2 : first)]
111 6 : (row->match-result result)))
112 :
113 : (find-by-match-ids
114 : [_ match-ids]
115 16 : (if (empty? match-ids)
116 1 : []
117 12 : (let [query (->
118 4 : base-query
119 52 : (assoc :where [:in :mr.match-id (mapv #(vector :cast % :uuid) match-ids)]))]
120 4 : (->>
121 12 : (sql/format query)
122 12 : (jdbc/execute! ds)
123 8 : (mapv row->match-result)))))
124 :
125 : (find-by-bracket-match-ids
126 : [_ bracket-match-ids]
127 4 : (if (empty? bracket-match-ids)
128 0 : []
129 1 : (let [query
130 10 : {:select [[:mr.uuid :uuid]
131 3 : [:mr.match-id :match-id]
132 3 : [:mr.winner-id :winner-id]
133 3 : [:mr.loser-id :loser-id]
134 3 : [:mr.ended-at :ended-at]
135 3 : [:mr.outcome :outcome]
136 3 : [:mr.home-score :home-score]
137 3 : [:mr.away-score :away-score]
138 3 : [:mr.extra :extra]
139 3 : [:mr.source :source]
140 6 : [[:coalesce :s.bracket-match-id :m.bracket-match-id] :bracket-match-id]]
141 4 : :from [[:match-results :mr]]
142 8 : :join [[:matches :m] [:= :mr.match-id :m.uuid]]
143 8 : :left-join [[:series :s] [:= :m.series-id :s.uuid]]
144 2 : :where [:or
145 12 : [:in :m.bracket-match-id (mapv #(vector :cast % :uuid) bracket-match-ids)]
146 3 : [:in
147 : :s.bracket-match-id
148 9 : (mapv #(vector :cast % :uuid) bracket-match-ids)]]}]
149 1 : (->>
150 3 : (sql/format query)
151 3 : (jdbc/execute! ds)
152 2 : (mapv utils.db/unqualify-keys)))))
153 :
154 : (search
155 : [_ filters pagination]
156 4 : (let [specs (filters->specs filters)
157 2 : query (qh/build-search-query
158 1 : base-query
159 1 : specs
160 1 : valid-sort-fields
161 1 : default-sort
162 1 : pagination
163 5 : {:sort-field-casts {:created-datetime :timestamptz}})
164 1 : rows (->>
165 3 : (sql/format query)
166 3 : (jdbc/execute! ds)
167 2 : (mapv row->match-result))
168 6 : opts (when-not (:cursor pagination)
169 5 : (let [cnt-query (qh/build-count-query base-query specs)
170 3 : total (->>
171 3 : (sql/format cnt-query)
172 3 : (jdbc/execute-one! ds)
173 1 : utils.db/unqualify-keys
174 : :total)]
175 3 : {:total-count total}))]
176 7 : (qh/paginate-results rows valid-sort-fields default-sort pagination opts)))
177 :
178 : (save!
179 : [_ match-result]
180 2 : (try
181 16 : (let [query {:insert-into :match_results
182 8 : :values [(match-result->row match-result)]
183 4 : :on-conflict [:match_id]
184 20 : :do-update-set {:fields [:winner_id
185 : :loser_id
186 : :ended_at
187 : :outcome
188 : :home_score
189 : :away_score
190 : :extra]}
191 4 : :returning [:*]}
192 2 : result (->>
193 10 : (sql/format (audit/stamp query))
194 6 : (jdbc/execute! ds)
195 2 : first)]
196 10 : (either/right (row->match-result result)))
197 : (catch Exception e
198 0 : (either/left
199 0 : (utils.errors/build-error
200 : :postgres
201 0 : {:message (.getMessage e)
202 0 : :context {:table :match_results
203 : :op :upsert
204 0 : :match-id (:match-id match-result)}})))))
205 :
206 : (delete-by-match-id!
207 : [_ match-id]
208 10 : (let [query {:delete-from :match_results
209 18 : :where [:= :match-id [:cast (str match-id) :uuid]]}]
210 2 : (->>
211 6 : (sql/format query)
212 4 : (jdbc/execute! ds)))))
213 :
214 :
215 4 : (defn make-repository
216 : "Creates a PostgresMatchResultRepository from a ds."
217 : [ds]
218 12 : (->PostgresMatchResultRepository ds))
|