LCOV - code coverage report
Current view: top level - matchscore/utils - pagination.clj Coverage Total Hit
Test: lcov.info Lines: 99.1 % 111 110
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.utils.pagination
       2              :   (:import
       3              :    [java.util Base64]))
       4              : 
       5              : 
       6            8 : (def default-limit 20)
       7              : 
       8              : 
       9            4 : (defn encode-cursor
      10              :  "Encodes sort-value and uuid into a base64 cursor string."
      11              :  [sort-value uuid]
      12           41 :  (let [raw (str (or sort-value "") "|" uuid)]
      13           20 :    (.encodeToString (Base64/getEncoder) (.getBytes raw "UTF-8"))))
      14              : 
      15              : 
      16            4 : (defn decode-cursor
      17              :  "Decodes a base64 cursor into [sort-value uuid]."
      18              :  [cursor]
      19           28 :  (let [raw  (String. (.decode (Base64/getDecoder) cursor) "UTF-8")
      20            8 :        idx  (.lastIndexOf raw "|")
      21           20 :        sval (subs raw 0 idx)
      22           20 :        uuid (subs raw (inc idx))]
      23           12 :    [sval uuid]))
      24              : 
      25              : 
      26            4 : (defn add-where-clause
      27              :  "Adds a raw WHERE clause to a HoneySQL query, combining with AND if one exists."
      28              :  [query clause]
      29           12 :  (update
      30            4 :   query
      31              :   :where
      32            4 :   (fn [w]
      33           28 :    (if w [:and w clause] clause))))
      34              : 
      35              : 
      36            4 : (defn- default-op
      37              :   "Returns the default operator for a value: :in for collections, := otherwise."
      38              :   [value]
      39            6 :   (if (sequential? value) :in :=))
      40              : 
      41              : 
      42            4 : (defn add-where
      43              :  "Adds a WHERE clause to a HoneySQL query.
      44              :    Supports two arities:
      45              :    - [query col value]        — auto-selects := or :in based on value type
      46              :    - [query col op value]     — uses the given operator explicitly"
      47            8 :  ([query col value] (add-where query col (default-op value) value))
      48           28 :  ([query col op value] (add-where-clause query [op col value])))
      49              : 
      50              : 
      51            4 : (defn- parse-filter-spec
      52              :   "Parses a filter spec into [col op value].
      53              :    Accepts [col value] (auto-detects op) or [col op value]."
      54              :   [spec]
      55           32 :   (if (= 3 (count spec)) spec (let [[col value] spec] [col (default-op value) value])))
      56              : 
      57              : 
      58            4 : (defn- empty-filter-value?
      59              :   "Returns true if the filter value should be skipped."
      60              :   [value]
      61           69 :   (or (nil? value) (and (sequential? value) (empty? value))))
      62              : 
      63              : 
      64            4 : (defn- con-clause
      65              :   "Builds an ILIKE clause for partial string match.
      66              :   col may be a single keyword or a vector of keywords.
      67              :   Vector: CONCAT_WS(' ', col1, col2, ...) ILIKE '%value%'
      68              :   Single: col ILIKE '%value%'"
      69              :   [col value]
      70           12 :   (let [pattern (str "%" value "%")
      71           24 :         expr    (if (sequential? col) (into [:concat_ws [:inline " "]] col) col)]
      72            8 :     [:ilike expr pattern]))
      73              : 
      74              : 
      75            4 : (defn apply-filters
      76              :  "Applies a sequence of filter specs to a base query.
      77              :   Each spec is either [column value] or [column operator value].
      78              :   For 2-element specs, auto-selects := or :in based on value type.
      79              :   Skips entries where value is nil or empty collection."
      80              :  [query filter-specs]
      81            8 :  (reduce
      82            4 :   (fn [q spec]
      83           16 :    (let [[col op value] (parse-filter-spec spec)]
      84           24 :      (cond (= op :con)
      85           22 :            (if (empty-filter-value? value) q (add-where-clause q (con-clause col value)))
      86              : 
      87           36 :            (and (empty-filter-value? value) (not (#{:is :is-not} op))) q
      88           24 :            :else (add-where q col op value))))
      89            4 :   query
      90            4 :   filter-specs))
      91              : 
      92              : 
      93            4 : (def ^:private graphql-op->sql-op
      94              :   "Maps GraphQL filter operator keys to SQL operators."
      95           60 :   {:eq  :=
      96              :    :in  :in
      97              :    :nin :not-in
      98              :    :gt  :>
      99              :    :gte :>=
     100              :    :lt  :<
     101              :    :lte :<=})
     102              : 
     103              : 
     104            4 : (defn typed-filter->specs
     105              :  "Converts a typed GraphQL filter map into a seq of [column op value] specs.
     106              :    A typed filter is {op value}, e.g. {:eq \"Kyiv\"} or {:in [\"UA\" \"PL\"]} or {:gte 5}.
     107              :    Returns specs for all non-nil operator entries.
     108              : 
     109              :    Example:
     110              :      (typed-filter->specs :city {:eq \"Kyiv\"})
     111              :      ;; => [[:city := \"Kyiv\"]]
     112              : 
     113              :      (typed-filter->specs :rating {:gte 4 :lte 10})
     114              :      ;; => [[:rating :>= 4] [:rating :<= 10]]"
     115              :  [col filter-map]
     116           12 :  (when filter-map
     117            8 :    (reduce-kv
     118            4 :     (fn [specs op value]
     119           28 :      (cond (= op :null) (conj specs [col (if value :is :is-not) nil])
     120              : 
     121           36 :            (= op :con) (if (nil? value) specs (conj specs [col :con value]))
     122              : 
     123           70 :            (or (nil? value) (and (sequential? value) (empty? value))) specs
     124              : 
     125              :            :else
     126           32 :            (if-let [sql-op (graphql-op->sql-op op)]
     127           28 :              (conj specs [col sql-op value])
     128            0 :              specs)))
     129            4 :     []
     130            4 :     filter-map)))
     131              : 
     132              : 
     133            4 : (defn- group-con-specs
     134              :   "Groups :con specs by value so columns sharing the same search term are
     135              :   combined into a single CONCAT_WS ILIKE clause.
     136              :   [{:col :first-name :con \"Jo\"} {:col :last-name :con \"Jo\"}]
     137              :   => [[:first-name :last-name] :con \"Jo\"]"
     138              :   [peq-specs]
     139            8 :   (map
     140            4 :    (fn [[value col-specs]]
     141           28 :     (let [cols (mapv first col-specs)] [(if (= 1 (count cols)) (first cols) cols) :con value]))
     142           22 :    (group-by #(nth % 2) peq-specs)))
     143              : 
     144              : 
     145            4 : (defn typed-filters->specs
     146              :  "Converts a map of {column typed-filter-map} into a flat seq of filter specs.
     147              :    :con specs sharing the same value across columns are grouped into a single
     148              :    CONCAT_WS ILIKE spec automatically.
     149              : 
     150              :    Example:
     151              :      (typed-filters->specs {:city {:eq \"Kyiv\"} :rating {:gte 4 :lte 10}})
     152              :      ;; => [[:city := \"Kyiv\"] [:rating :>= 4] [:rating :<= 10]]
     153              : 
     154              :      (typed-filters->specs {:first-name {:con \"Jo\"} :last-name {:con \"Jo\"}})
     155              :      ;; => [[[:first-name :last-name] :con \"Jo\"]]
     156              : 
     157              :      (typed-filters->specs {:first-name {:con \"Jo\"} :last-name {:con \"Doe\"}})
     158              :      ;; => [[:first-name :con \"Jo\"] [:last-name :con \"Doe\"]]"
     159              :  [filters]
     160           12 :  (let [all-specs (reduce-kv
     161            4 :                   (fn [specs col filter-map]
     162           28 :                    (into specs (typed-filter->specs col filter-map)))
     163            4 :                   []
     164            4 :                   filters)
     165              :        {peq-specs   true
     166              :         other-specs false}
     167           36 :        (group-by #(= :con (second %)) all-specs)]
     168           32 :    (into (vec other-specs) (group-con-specs peq-specs))))
     169              : 
     170              : 
     171            4 : (defn- cursor-mode?
     172              :   "Returns true if pagination uses cursor-based mode."
     173              :   [{:keys [cursor]}]
     174           12 :   (some? cursor))
     175              : 
     176              : 
     177            4 : (defn build-search-query
     178              :  "Builds a HoneySQL search query with filtering, sorting, and pagination.
     179              :    Supports two modes:
     180              :    - Cursor-based: when :cursor is present, uses keyset pagination (N+1 fetch)
     181              :    - Offset-based: when :offset is present (no cursor), uses LIMIT/OFFSET
     182              :    If neither cursor nor offset, returns first page.
     183              : 
     184              :    - base-query:        base HoneySQL map (e.g. {:select [:*] :from [:clubs]})
     185              :    - filter-specs:      seq of [column value] pairs for WHERE clauses
     186              :    - valid-sort-fields: set of allowed sort keywords
     187              :    - default-sort:      fallback sort field keyword
     188              :    - pagination:        {:limit N :cursor \"...\" :offset N :sort-by :field :sort-dir :asc|:desc}
     189              :    - opts:              optional map:
     190              :                           :sort-field-casts — map of sort field keyword → SQL cast type keyword
     191              :                                               (e.g. {:match-number :integer :slot :smallint})
     192              :                                               used to cast the decoded cursor sort value to the
     193              :                                               correct SQL type when building keyset pagination.
     194              :                           :sort-col-exprs   — map of sort field keyword → HoneySQL column expression
     195              :                                               used when the column name is a SQL reserved word that
     196              :                                               must be quoted in the composite row comparison
     197              :                                               (e.g. {:order [:raw \"\\\"order\\\"\"]})"
     198              :  ([base-query filter-specs valid-sort-fields default-sort pagination]
     199           32 :   (build-search-query base-query filter-specs valid-sort-fields default-sort pagination {}))
     200              :  ([base-query
     201              :    filter-specs
     202              :    valid-sort-fields
     203              :    default-sort
     204              :    {:keys [limit cursor offset sort-by sort-dir]
     205              :     :as   pagination}
     206              :    {:keys [sort-field-casts sort-col-exprs]}]
     207           27 :   (let [sort-col      (if (valid-sort-fields sort-by) sort-by default-sort)
     208           16 :         sort-col-expr (get sort-col-exprs sort-col sort-col)
     209           24 :         direction     (if (= sort-dir :desc) :desc :asc)
     210           24 :         take-n        (or limit default-limit)
     211           16 :         filtered      (apply-filters base-query filter-specs)]
     212           16 :     (if (cursor-mode? pagination)
     213              :       ;; Cursor-based: fetch N+1 for has-next-page detection
     214           20 :       (let [with-cursor (let [[sort-val cursor-uuid] (decode-cursor cursor)
     215           12 :                               sort-cast (get sort-field-casts sort-col)
     216           28 :                               sort-val-expr (if sort-cast [:cast sort-val sort-cast] sort-val)
     217           22 :                               op (if (= direction :asc) :> :<)]
     218            8 :                           (add-where-clause
     219            4 :                            filtered
     220            8 :                            [op
     221           16 :                             [:composite sort-col-expr :uuid]
     222           28 :                             [:composite sort-val-expr [:cast cursor-uuid :uuid]]]))]
     223           20 :         (assoc with-cursor
     224           28 :          :order-by [[sort-col-expr direction] [:uuid direction]]
     225            8 :          :limit    (inc take-n)))
     226              :       ;; Offset-based: use LIMIT/OFFSET, fetch N+1 for has-next-page
     227           18 :       (cond->
     228           20 :         (assoc filtered
     229           28 :          :order-by [[sort-col-expr direction] [:uuid direction]]
     230            8 :          :limit    (inc take-n))
     231           28 :         (and offset (pos? offset)) (assoc :offset offset))))))
     232              : 
     233              : 
     234            4 : (defn build-count-query
     235              :  "Builds a COUNT query from the same base-query and filter-specs.
     236              :    Used for offset-based pagination to return total-count."
     237              :  [base-query filter-specs]
     238            4 :  (->
     239           40 :    (assoc base-query :select [[[:count :*] :total]])
     240            8 :    (apply-filters filter-specs)))
     241              : 
     242              : 
     243            4 : (defn paginate-results
     244              :  "Takes query results and pagination params, returns paginated response.
     245              :    Always returns :items, :has-next-page, and :end-cursor.
     246              :    For offset mode, also returns :total-count.
     247              : 
     248              :    - rows:              vector of result maps
     249              :    - valid-sort-fields: set of allowed sort keywords
     250              :    - default-sort:      fallback sort field keyword
     251              :    - pagination:        {:limit N :sort-by :field :cursor \"...\" :offset N}
     252              :    - opts:              optional map with :total-count for offset mode"
     253              :  ([rows valid-sort-fields default-sort pagination]
     254            7 :   (paginate-results rows valid-sort-fields default-sort pagination nil))
     255              :  ([rows
     256              :    valid-sort-fields
     257              :    default-sort
     258              :    {:keys [limit sort-by]
     259              :     :as   pagination}
     260              :    opts]
     261           28 :   (let [take-n        (or limit default-limit)
     262           23 :         sort-col      (if (valid-sort-fields sort-by) sort-by default-sort)
     263           16 :         has-next-page (> (count rows) take-n)
     264           32 :         items         (if has-next-page (subvec rows 0 take-n) rows)
     265           20 :         end-cursor    (when (seq items)
     266           16 :                         (let [last-item (peek items)]
     267           32 :                           (encode-cursor (get last-item sort-col) (:uuid last-item))))]
     268           24 :     (cond->
     269           20 :       {:items         items
     270            4 :        :has-next-page has-next-page
     271            4 :        :end-cursor    end-cursor}
     272           36 :       (not (cursor-mode? pagination)) (assoc :total-count (:total-count opts))))))
        

Generated by: LCOV version 2.0-1