LCOV - code coverage report
Current view: top level - matchscore/domain/bracket/repository - postgres.clj Coverage Total Hit
Test: lcov.info Lines: 93.9 % 115 108
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.domain.bracket.repository.postgres
       2              :   (:require
       3              :    [cheshire.core :as json]
       4              :    [honey.sql :as sql]
       5              :    [matchscore.domain.bracket.entity :as entity]
       6              :    [matchscore.utils.audit :as audit]
       7              :    [matchscore.utils.db :as utils.db]
       8              :    [matchscore.utils.pagination :as qh]
       9              :    [next.jdbc :as jdbc]))
      10              : 
      11              : 
      12            4 : (defprotocol
      13              :   BracketPostgresRepository
      14              :   (find-by-id
      15              :    [this id]
      16              :    "Find bracket by UUID. Returns Bracket map or nil.")
      17              :   (find-by-ids
      18              :    [this ids]
      19              :    "Find brackets by multiple UUIDs. Returns seq.")
      20              :   (find-by-draw-id
      21              :    [this draw-id]
      22              :    "Find all brackets for a draw. Returns seq.")
      23              :   (find-by-draw-ids
      24              :    [this draw-ids]
      25              :    "Find all brackets for multiple draws in one batch query. Returns seq.")
      26              :   (search
      27              :    [this filters pagination]
      28              :    "Search brackets. filters: {:drawId {...}}. sort: #{:name}, default: :name")
      29              :   (insert!
      30              :    [this bracket-data]
      31              :    "Insert a new bracket. Returns [success? result-or-reason error-message].
      32              :     Returns [false :conflict-id ...] on UUID unique-constraint violation.")
      33              :   (upsert!
      34              :    [this bracket-data]
      35              :    "Upsert a bracket. Returns [success? result-or-reason error-message].")
      36              :   (delete!
      37              :    [this id]
      38              :    "Delete a bracket by UUID. Returns true."))
      39              : 
      40              : 
      41            4 : (defn- filters->specs
      42              :   "Converts a GraphQL filters map to a seq of [column op value] specs."
      43              :   [{:keys [drawId]}]
      44            7 :   (qh/typed-filters->specs {:draw-id (utils.db/cast-uuid-filter drawId)}))
      45              : 
      46              : 
      47            4 : (defn- row->bracket
      48              :   "Converts a database row to a domain Bracket map."
      49              :   [row]
      50           32 :   (when row (entity/make-bracket (utils.db/unqualify-keys row))))
      51              : 
      52              : 
      53           12 : (def ^:private valid-sort-fields #{:name})
      54              : 
      55              : 
      56            8 : (def ^:private default-sort :name)
      57              : 
      58              : 
      59            4 : (def ^:private base-query
      60           28 :   {:select [[:b.uuid :uuid]
      61           12 :             [:b.public-id :public-id]
      62           12 :             [:b.draw-id :draw-id]
      63           12 :             [:b.name :name]
      64           12 :             [:b.type :type]
      65           12 :             [:b.ruleset-id :ruleset-id]
      66           12 :             [:b.config :config]
      67           12 :             [:b.created-datetime :created-datetime]
      68           12 :             [:b.source :source]]
      69           16 :    :from   [[:brackets :b]]})
      70              : 
      71              : 
      72              : ;; Brackets of a draw are shown in the order they are returned: the root bracket first,
      73              : ;; then by the places they decide. uuid (v7, creation order) breaks ties and covers brackets
      74              : ;; without a placement range.
      75           40 : (def ^:private draw-order [[[:raw "(b.config->>'placement-from')::int"] :asc] [:b.uuid :asc]])
      76              : 
      77              : 
      78            4 : (defrecord
      79              :   PostgresBracketRepository
      80              :   [ds]
      81              :   BracketPostgresRepository
      82              : 
      83              :   (find-by-id
      84              :    [_ id]
      85           48 :    (let [query  (assoc base-query :where [:= :b.uuid [:cast id :uuid]])
      86            4 :          result (->>
      87           12 :                   (sql/format query)
      88           12 :                   (jdbc/execute! ds)
      89            4 :                   first)]
      90           12 :      (row->bracket result)))
      91              : 
      92              :   (find-by-ids
      93              :    [_ ids]
      94            4 :    (if (empty? ids)
      95            0 :      []
      96           17 :      (let [query (assoc base-query :where [:in :b.uuid (mapv #(vector :cast % :uuid) ids)])]
      97            1 :        (->>
      98            3 :          (sql/format query)
      99            3 :          (jdbc/execute! ds)
     100            2 :          (mapv row->bracket)))))
     101              : 
     102              :   (find-by-draw-id
     103              :    [_ draw-id]
     104           24 :    (let [query (assoc base-query
     105           28 :                 :where    [:= :b.draw-id [:cast draw-id :uuid]]
     106            4 :                 :order-by draw-order)]
     107            4 :      (->>
     108           12 :        (sql/format query)
     109           12 :        (jdbc/execute! ds)
     110            8 :        (mapv row->bracket))))
     111              : 
     112              :   (find-by-draw-ids
     113              :    [_ draw-ids]
     114            8 :    (if (empty? draw-ids)
     115            0 :      []
     116           12 :      (let [query (assoc base-query
     117           24 :                   :where    [:in :b.draw-id (mapv #(vector :cast % :uuid) draw-ids)]
     118            2 :                   :order-by draw-order)]
     119            2 :        (->>
     120            6 :          (sql/format query)
     121            6 :          (jdbc/execute! ds)
     122            4 :          (mapv row->bracket)))))
     123              : 
     124              :   (search
     125              :    [_ filters pagination]
     126            4 :    (let [specs (filters->specs filters)
     127            7 :          query (qh/build-search-query base-query specs valid-sort-fields default-sort pagination)
     128            1 :          rows  (->>
     129            3 :                  (sql/format query)
     130            3 :                  (jdbc/execute! ds)
     131            2 :                  (mapv row->bracket))
     132            6 :          opts  (when-not (:cursor pagination)
     133            5 :                  (let [cnt-query (qh/build-count-query base-query specs)
     134            3 :                        total     (->>
     135            3 :                                    (sql/format cnt-query)
     136            3 :                                    (jdbc/execute-one! ds)
     137            1 :                                    utils.db/unqualify-keys
     138              :                                    :total)]
     139            3 :                    {:total-count total}))]
     140            7 :      (qh/paginate-results rows valid-sort-fields default-sort pagination opts)))
     141              : 
     142              :   (insert!
     143              :    [_ bracket-data]
     144            3 :    (try
     145            6 :      (let [{:keys [uuid public-id draw-id name type ruleset-id config source]} bracket-data
     146           15 :            query  {:insert-into :brackets
     147           42 :                    :values      [{:uuid       [:cast uuid :uuid]
     148            3 :                                   :public_id  public-id
     149           12 :                                   :draw_id    [:cast draw-id :uuid]
     150            3 :                                   :name       name
     151            3 :                                   :type       type
     152            6 :                                   :ruleset_id (when ruleset-id [:cast ruleset-id :uuid])
     153           30 :                                   :config     [:cast (json/generate-string (or config {})) :jsonb]
     154           15 :                                   :source     (or source "matchscore")}]
     155            6 :                    :returning   [:*]}
     156            6 :            result (->>
     157           15 :                     (sql/format (audit/stamp query))
     158            9 :                     (jdbc/execute! ds)
     159            3 :                     first
     160            3 :                     row->bracket)]
     161           12 :        [true result nil])
     162              :      (catch org.postgresql.util.PSQLException e
     163            0 :        (if (= "23505" (.getSQLState e))
     164            0 :          [false :conflict-id "Bracket with such id already exists"]
     165            0 :          [false :database-error (.getMessage e)]))
     166            0 :      (catch Exception e [false :database-error (.getMessage e)])))
     167              : 
     168              :   (upsert!
     169              :    [_ bracket-data]
     170            2 :    (try
     171            4 :      (let [{:keys [uuid public-id draw-id name type ruleset-id config source]} bracket-data
     172           14 :            query  {:insert-into   :brackets
     173           28 :                    :values        [{:uuid       [:cast uuid :uuid]
     174            2 :                                     :public_id  public-id
     175            8 :                                     :draw_id    [:cast draw-id :uuid]
     176            2 :                                     :name       name
     177            2 :                                     :type       type
     178            4 :                                     :ruleset_id (when ruleset-id [:cast ruleset-id :uuid])
     179           21 :                                     :config     [:cast (json/generate-string (or config {})) :jsonb]
     180           10 :                                     :source     (or source "matchscore")}]
     181            4 :                    :on-conflict   [:uuid]
     182           16 :                    :do-update-set {:fields [:draw_id :name :type :ruleset_id :config]}
     183            4 :                    :returning     [:*]}
     184            4 :            result (->>
     185           10 :                     (sql/format (audit/stamp query))
     186            6 :                     (jdbc/execute! ds)
     187            2 :                     first
     188            2 :                     row->bracket)]
     189            8 :        [true result nil])
     190            0 :      (catch Exception e [false :database-error (.getMessage e)])))
     191              : 
     192            1 :   (delete!
     193              :    [_ id]
     194            5 :    (let [query {:delete-from :brackets
     195            7 :                 :where       [:= :uuid [:cast id :uuid]]}]
     196            1 :      (->>
     197            3 :        (sql/format query)
     198            2 :        (jdbc/execute! ds)))
     199              :    true))
     200              : 
     201              : 
     202            4 : (defn make-repository
     203              :  "Creates a PostgresBracketRepository from a ds."
     204              :  [ds]
     205           12 :  (->PostgresBracketRepository ds))
        

Generated by: LCOV version 2.0-1