Line data Source code
1 4 : (ns matchscore.domain.player-follow.repository.postgres
2 : "Players a user follows on the imported tours (PSA, ESF).
3 :
4 : Each source keeps its own follow table keyed on the source's stable player id:
5 : - psa: psa_players.psa_id (integer)
6 : - esf: the ESF id (ESID number), shared by ranking entries and imported draws
7 :
8 : Keys travel as strings outside this namespace; `parse-key` validates them.
9 :
10 : Players from excluded countries (`country-exclusion`) are treated as unknown:
11 : they can't be followed and existing follows of them are not listed."
12 : (:require
13 : [clojure.string :as str]
14 : [matchscore.db.postgres.user-updates :as user-updates]
15 : [matchscore.domain.country-exclusion :as country-exclusion]
16 : [matchscore.domain.player-follow.profile :as profile]
17 : [matchscore.domain.player-follow.rankings :as rankings]
18 : [matchscore.search.players :as search-players]
19 : [next.jdbc :as jdbc]
20 : [next.jdbc.result-set :as rs]))
21 :
22 :
23 16 : (def sources #{"psa" "esf"})
24 :
25 :
26 4 : (defn parse-key
27 : "Returns the key in the type the source's table stores, or nil when malformed."
28 : [source raw]
29 32 : (let [raw (some->
30 2 : raw
31 2 : str
32 2 : str/trim)]
33 10 : (when-not (str/blank? raw)
34 6 : (case source
35 18 : "psa" (when (re-matches #"[0-9]{1,9}" raw) (parse-long raw))
36 : ;; Ranking pages show "ES662969162"; draws store the bare number.
37 10 : "esf" (when-let [[_ digits] (re-matches #"(?i)(?:ES)?([0-9]{1,12})" raw)]
38 9 : (let [esid (parse-long digits)] (when (pos? esid) esid)))
39 : nil))))
40 :
41 :
42 4 : (def ^:private draw-players-join
43 : "From events `e` to the source's player columns: player_id, full_name, country_code,
44 : photo_url, joined to the user's follows as `f` (first placeholder: user id)."
45 20 : {"psa"
46 : "JOIN psa_players pp ON pp.rankedin_user_id = p.user_id_rankedin
47 : JOIN psa_player_follows f ON f.psa_player_id = pp.psa_id AND f.user_id = ?::uuid"
48 : "esf"
49 : "JOIN rankedin_users ru ON ru.uuid = p.user_id_rankedin AND ru.source = 'esf'
50 : JOIN esf_player_follows f ON f.esid = ru.rankedin_id AND f.user_id = ?::uuid"})
51 :
52 :
53 4 : (def ^:private draw-players-country
54 : "The country of a draw player, as `profile` resolves it (ESF: newest ranking entry,
55 : else the draw user)."
56 20 : {"psa" "pp.country_code"
57 : "esf"
58 : "COALESCE((SELECT country_code FROM esf_ranking_entries
59 : WHERE esid = 'ES' || ru.rankedin_id::text
60 : ORDER BY publication_id DESC LIMIT 1),
61 : ru.country_code)"})
62 :
63 :
64 4 : (def ^:private draw-players-select
65 20 : {"psa" "pp.psa_id::text AS player_id, pp.full_name, pp.country_code, pp.photo_url"
66 : "esf"
67 : "ru.rankedin_id::text AS player_id,
68 : trim(concat_ws(' ', ru.first_name, ru.last_name)) AS full_name,
69 : ru.country_code, ru.photo_url"})
70 :
71 :
72 4 : (def ^:private tables
73 40 : {"psa" {:table "psa_player_follows"
74 : :column "psa_player_id"
75 : :cast ""}
76 28 : "esf" {:table "esf_player_follows"
77 : :column "esid"
78 : :cast ""}})
79 :
80 :
81 4 : (def ^:private exists-sql
82 : "One placeholder: the player key. An ESF id is known if it is in a ranking or an
83 : imported draw; its country is the newest ranking entry's, else the draw user's."
84 24 : {"psa" (str
85 : "SELECT 1 FROM psa_players WHERE psa_id = ? AND "
86 12 : (country-exclusion/allowed-sql "country_code"))
87 : "esf"
88 12 : (str
89 : "SELECT 1
90 : FROM (SELECT ?::bigint AS esid) k
91 : LEFT JOIN LATERAL (
92 : SELECT true AS found, country_code
93 : FROM esf_ranking_entries
94 : WHERE esid = 'ES' || k.esid::text
95 : ORDER BY publication_id DESC
96 : LIMIT 1) re ON true
97 : LEFT JOIN LATERAL (
98 : SELECT true AS found, country_code
99 : FROM rankedin_users
100 : WHERE source = 'esf' AND rankedin_id = k.esid
101 : LIMIT 1) ru ON true
102 : WHERE (re.found OR ru.found) AND "
103 12 : (country-exclusion/allowed-sql "COALESCE(re.country_code, ru.country_code)"))})
104 :
105 :
106 4 : (defprotocol
107 : PlayerFollowPostgresRepository
108 : (player-exists?
109 : [this source player-key])
110 : (follow!
111 : [this source user-id player-key])
112 : (unfollow!
113 : [this source user-id player-key])
114 : (find-followed-keys
115 : [this source user-id]
116 : "Set of followed player keys, as strings.")
117 : (find-followed-players-by-event
118 : [this source user-id event-public-ids]
119 : "Map of event public id → followed players found in that imported event.")
120 : (find-followed-players
121 : [this user-id]
122 : "Every player the user follows, on all sources, newest follow first.")
123 : (find-player-profile
124 : [this source player-id]
125 : "Profile of an imported player (rankedin, fsu, psa, esf), or nil.")
126 : (find-current-rankings
127 : [this source player-ids]
128 : "Map of player id → current rankings of that player on source, best first.")
129 : (search-players
130 : [this source query limit]
131 : [this source query limit exclude]
132 : "Players of source (psa, esf, rankedin, fsu, all) whose name matches
133 : query, best first; exclude lists sources an \"all\" search leaves out."))
134 :
135 :
136 16 : (def ^:private query-options {:builder-fn rs/as-unqualified-kebab-maps})
137 :
138 :
139 4 : (def ^:private followed-players-sql
140 : "One row per follow: source, player_id (the follow key), name, country, photo,
141 : profile link and when it was followed. ESF names come from the newest ranking
142 : entry with that ESF id, else from an imported draw. Players from excluded
143 : countries are left out."
144 20 : (str
145 : "SELECT 'psa' AS source, pp.psa_id::text AS player_id, pp.full_name, pp.country_code,
146 : pp.photo_url, NULL::text AS profile_url, f.created_datetime AS followed_at
147 : FROM psa_player_follows f
148 : JOIN psa_players pp ON pp.psa_id = f.psa_player_id
149 : WHERE f.user_id = ?::uuid AND "
150 12 : (country-exclusion/allowed-sql "pp.country_code")
151 : "
152 : UNION ALL
153 : SELECT 'esf', f.esid::text,
154 : COALESCE(re.full_name, NULLIF(trim(concat_ws(' ', ru.first_name, ru.last_name)), ''),
155 : 'ES' || f.esid::text),
156 : COALESCE(re.country_code, ru.country_code), ru.photo_url,
157 : COALESCE(re.profile_url, ru.profile_url), f.created_datetime
158 : FROM esf_player_follows f
159 : LEFT JOIN LATERAL (
160 : SELECT full_name, country_code, profile_url
161 : FROM esf_ranking_entries
162 : WHERE esid = 'ES' || f.esid::text
163 : ORDER BY publication_id DESC
164 : LIMIT 1) re ON true
165 : LEFT JOIN LATERAL (
166 : SELECT first_name, last_name, country_code, photo_url, profile_url
167 : FROM rankedin_users
168 : WHERE source = 'esf' AND rankedin_id = f.esid
169 : LIMIT 1) ru ON true
170 : WHERE f.user_id = ?::uuid AND "
171 12 : (country-exclusion/allowed-sql "COALESCE(re.country_code, ru.country_code)")
172 : "
173 : ORDER BY followed_at DESC, full_name"))
174 :
175 :
176 4 : (defrecord
177 : PostgresPlayerFollowRepository
178 : [ds meilisearch]
179 : PlayerFollowPostgresRepository
180 : (player-exists?
181 : [_ source player-key]
182 11 : (some? (jdbc/execute-one! ds [(exists-sql source) player-key] query-options)))
183 : (follow!
184 : [_ source user-id player-key]
185 10 : (let [{:keys [table column cast]} (tables source)]
186 8 : (jdbc/with-transaction
187 2 : [tx ds]
188 26 : (when (contains? #{"psa" "esf"} source) (user-updates/flush-user! tx user-id source))
189 : ;; No backfill: mark what is already true as seeded, in the same transaction, only when
190 : ;; this request really added the follow (a repeated follow seeds nothing).
191 4 : (when
192 10 : (and
193 2 : (pos?
194 8 : (or
195 4 : (:next.jdbc/update-count
196 4 : (jdbc/execute-one!
197 2 : tx
198 16 : [(str
199 2 : "INSERT INTO " table
200 2 : " (user_id, " column
201 2 : ") VALUES (?::uuid, ?" cast
202 : ") " "ON CONFLICT DO NOTHING")
203 2 : user-id
204 2 : player-key]))
205 : 0))
206 10 : (contains? #{"psa" "esf"} source))
207 4 : (user-updates/seed!
208 2 : tx
209 2 : user-id
210 10 : {:type :follow
211 2 : :source source
212 6 : :player-key (str player-key)})))
213 : true))
214 : (unfollow!
215 : [_ source user-id player-key]
216 10 : (let [{:keys [table column cast]} (tables source)]
217 4 : (jdbc/execute-one!
218 2 : ds
219 18 : [(str "DELETE FROM " table " WHERE user_id = ?::uuid AND " column " = ?" cast)
220 2 : user-id
221 2 : player-key])
222 : false))
223 : (find-followed-keys
224 : [_ source user-id]
225 4 : (let [{:keys [table column]} (tables source)]
226 2 : (into
227 1 : #{}
228 3 : (map :player-key)
229 2 : (jdbc/execute!
230 1 : ds
231 8 : [(str "SELECT " column "::text AS player_key FROM " table " WHERE user_id = ?::uuid")
232 1 : user-id]
233 1 : query-options))))
234 : (find-followed-players-by-event
235 : [_ source user-id event-public-ids]
236 9 : (let [ids (vec (distinct (remove nil? event-public-ids)))]
237 4 : (if (empty? ids)
238 1 : {}
239 10 : (let [sql (str
240 : "SELECT DISTINCT e.public_id AS event_public_id, "
241 3 : (draw-players-select source)
242 : " FROM events e"
243 : " JOIN event_participants ep ON ep.event_id = e.uuid"
244 : " JOIN participants p ON p.uuid = ep.participant_id "
245 3 : (draw-players-join source)
246 : " WHERE e.public_id IN ("
247 8 : (str/join ", " (repeat (count ids) "?"))
248 : ") AND "
249 5 : (country-exclusion/allowed-sql (draw-players-country source))
250 : " ORDER BY event_public_id, full_name")
251 10 : rows (jdbc/execute! ds (into [sql user-id] ids) query-options)]
252 2 : (reduce
253 1 : (fn
254 : [acc
255 : {:keys [event-public-id]
256 : :as row}]
257 12 : (update acc event-public-id (fnil conj []) (dissoc row :event-public-id)))
258 1 : {}
259 1 : rows)))))
260 : (find-followed-players
261 : [_ user-id]
262 3 : (mapv
263 4 : #(update
264 : %
265 : :followed-at
266 1 : (fn [ts]
267 3 : (when ts
268 8 : (str (if (instance? java.sql.Timestamp ts) (.toInstant ^java.sql.Timestamp ts) ts)))))
269 8 : (jdbc/execute! ds [followed-players-sql user-id user-id] query-options)))
270 5 : (find-player-profile [_ source player-id] (profile/find-player-profile ds source player-id))
271 5 : (find-current-rankings [_ source player-ids] (rankings/current-rankings ds source player-ids))
272 : (search-players
273 : [_ source query limit]
274 8 : (search-players/search-players ds meilisearch source query limit nil))
275 : (search-players
276 : [_ source query limit exclude]
277 8 : (search-players/search-players ds meilisearch source query limit exclude)))
278 :
279 :
280 4 : (defn make-repository
281 : "Creates a PostgresPlayerFollowRepository from a datasource. With a Meilisearch
282 : client, player search uses the search index (falling back to Postgres)."
283 16 : ([ds] (make-repository ds nil))
284 16 : ([ds meilisearch] (->PostgresPlayerFollowRepository ds meilisearch)))
|