Line data Source code
1 4 : (ns matchscore.db.postgres.host
2 : (:require
3 : [next.jdbc :as jdbc]
4 : [next.jdbc.result-set :as rs]))
5 :
6 :
7 4 : (def ^:private resources
8 28 : {:event ["events" "event_participants" "event_id"]
9 16 : :template ["templates" "template_participants" "template_id"]})
10 :
11 :
12 4 : (defn set-host!
13 : "Select an existing participant admin, or clear the host. Lock the membership
14 : until the host write commits so concurrent demotion/removal clears it reliably.
15 : General resource saves deliberately never write this column."
16 : [ds kind resource-id user-id]
17 1 : (let [[table members foreign-key]
18 7 : (or (resources kind) (throw (IllegalArgumentException. "Unknown host resource")))]
19 4 : (jdbc/with-transaction
20 1 : [tx ds]
21 1 : (if
22 7 : (and
23 1 : user-id
24 : (nil?
25 2 : (jdbc/execute-one!
26 1 : tx
27 9 : [(str
28 1 : "SELECT m.participant_id FROM " members
29 : " m " "JOIN participants p ON p.uuid = m.participant_id "
30 1 : "WHERE m." foreign-key
31 : " = ?::uuid AND p.user_id = ?::uuid "
32 : "AND m.roles @> '[\"admin\"]'::jsonb FOR UPDATE OF m")
33 1 : resource-id
34 1 : user-id])))
35 3 : {:error :error.host/not-admin}
36 7 : (if-let [row (jdbc/execute-one!
37 1 : tx
38 6 : [(str
39 1 : "UPDATE " table
40 : " SET host_user_id = ?::uuid, updated_datetime = now() "
41 : "WHERE uuid = ?::uuid RETURNING host_user_id")
42 1 : user-id
43 1 : resource-id]
44 3 : {:builder-fn rs/as-unqualified-kebab-maps})]
45 11 : {:host-user-id (some->
46 3 : (:host-user-id row)
47 1 : str)}
48 0 : {:error :error.host/not-found})))))
49 :
50 :
51 4 : (defn inherit-template-host!
52 : "Called after template admins are copied, inside event creation's transaction."
53 : [tx event-id template-id]
54 3 : (let
55 : [row
56 6 : (jdbc/execute-one!
57 3 : tx
58 6 : ["UPDATE events e SET host_user_id = t.host_user_id
59 : FROM templates t
60 : WHERE e.uuid = ?::uuid AND t.uuid = ?::uuid
61 : AND t.host_user_id IS NOT NULL
62 : AND EXISTS (SELECT 1 FROM event_participants ep
63 : JOIN participants p ON p.uuid = ep.participant_id
64 : WHERE ep.event_id = e.uuid AND p.user_id = t.host_user_id
65 : AND ep.roles @> '[\"admin\"]'::jsonb)
66 : RETURNING e.host_user_id"
67 3 : event-id
68 3 : template-id]
69 9 : {:builder-fn rs/as-unqualified-kebab-maps})]
70 23 : (some->
71 9 : (:host-user-id row)
72 1 : str)))
|