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

            Line data    Source code
       1              : ;!zprint {:format :off}
       2            4 : (ns matchscore.domain.telegram-chat-message.repository.postgres
       3              :   (:require
       4              :    [cats.monad.either :as either]
       5              :    [honey.sql :as sql]
       6              :    [next.jdbc :as jdbc]
       7              :    [matchscore.domain.telegram-chat-message.entity :as entity]
       8              :    [matchscore.utils.db :as utils.db]
       9              :    [matchscore.utils.errors :as utils.errors]))
      10              : 
      11              : 
      12              : ;!zprint {:format :on}
      13              : 
      14              : 
      15            4 : (defprotocol
      16              :   TelegramChatMessagePostgresRepository
      17              :   (record!
      18              :    [this msg]
      19              :    "Records a chat message. Idempotent on (chat_id, message_id).
      20              :       Returns Either<Error, TelegramChatMessage>.")
      21              :   (find-undeleted-for-event
      22              :    [this event-id]
      23              :    "Returns all undeleted messages tied to the event (vec of maps).")
      24              :   (find-undeleted-for-template
      25              :    [this template-id]
      26              :    "Returns all undeleted messages tied to the template (vec of maps).")
      27              :   (find-by-event-id
      28              :    [this event-id]
      29              :    "Returns all messages tied to the event (vec of maps).")
      30              :   (find-by-event-ids
      31              :    [this event-ids]
      32              :    "Batch fetch messages for multiple events.")
      33              :   (find-by-template-id
      34              :    [this template-id]
      35              :    "Returns all messages tied to the template (vec of maps).")
      36              :   (find-by-template-ids
      37              :    [this template-ids]
      38              :    "Batch fetch messages for multiple templates.")
      39              :   (mark-deleted!
      40              :    [this uuids]
      41              :    "Marks rows as deleted (sets deleted_at = now()). Idempotent."))
      42              : 
      43              : 
      44           36 : (defn- row->msg [row] (when row (entity/make-telegram-chat-message (utils.db/unqualify-keys row))))
      45              : 
      46              : 
      47            4 : (def ^:private message-select
      48           16 :   [[:tcm.uuid :uuid]
      49           12 :    [:tcm.chat-id :chat-id]
      50           24 :    [[:coalesce :tel.chat-title :ttl.chat-title] :chat-title]
      51           12 :    [:tcm.thread-id :thread-id]
      52           12 :    [:tcm.message-id :message-id]
      53           12 :    [:tcm.sender-kind :sender-kind]
      54           12 :    [:tcm.sender-tg-id :sender-tg-id]
      55           12 :    [:u.name :sender-name]
      56           12 :    [:tcm.user-id :user-id]
      57           12 :    [:tcm.kind :kind]
      58           12 :    [:tcm.command :command]
      59           12 :    [:tcm.message-text :message-text]
      60           12 :    [:tcm.content-revision :content-revision]
      61           12 :    [:tcm.event-id :event-id]
      62           12 :    [:tcm.template-id :template-id]
      63           12 :    [:tcm.deleted-at :deleted-at]
      64           12 :    [:tcm.created-datetime :created-datetime]])
      65              : 
      66              : 
      67           20 : (def ^:private message-from [[:telegram-chat-messages :tcm]])
      68              : 
      69              : 
      70            4 : (def ^:private user-join
      71           16 :   [[:users :u]
      72            8 :    [:or
      73           16 :     [:= :tcm.user-id :u.uuid]
      74           40 :     [:and [:is :tcm.user-id nil] [:= :tcm.sender-tg-id :u.telegram-id]]]])
      75              : 
      76              : 
      77            4 : (def ^:private link-joins
      78           16 :   [[:telegram-event-links :tel]
      79            8 :    [:and
      80           16 :     [:= :tcm.event-id :tel.event-id]
      81           16 :     [:= :tcm.chat-id :tel.chat-id]
      82           16 :     [:= :tcm.thread-id :tel.thread-id]]
      83           12 :    [:telegram-template-links :ttl]
      84            8 :    [:and
      85           16 :     [:= :tcm.template-id :ttl.template-id]
      86           16 :     [:= :tcm.chat-id :ttl.chat-id]
      87           16 :     [:= :tcm.thread-id :ttl.thread-id]]])
      88              : 
      89              : 
      90            4 : (defn- message-query
      91              :   [query]
      92            8 :   (merge
      93           20 :    {:select    message-select
      94            4 :     :from      message-from
      95           16 :     :left-join (into user-join link-joins)}
      96            4 :    query))
      97              : 
      98              : 
      99            4 : (defn- msg->row
     100              :   [{:keys [chat-id
     101              :            thread-id
     102              :            message-id
     103              :            sender-kind
     104              :            sender-tg-id
     105              :            user-id
     106              :            kind
     107              :            command
     108              :            text
     109              :            content-revision
     110              :            event-id
     111              :            template-id]}]
     112           83 :   (cond->
     113           28 :     {:chat_id     chat-id
     114           22 :      :thread_id   (or thread-id -1)
     115            4 :      :message_id  message-id
     116            4 :      :sender_kind sender-kind
     117            4 :      :kind        kind}
     118           16 :     sender-tg-id     (assoc :sender_tg_id sender-tg-id)
     119           25 :     user-id          (assoc :user_id [:cast user-id :uuid])
     120           16 :     command          (assoc :command command)
     121           20 :     text             (assoc :message_text text)
     122           16 :     content-revision (assoc :content_revision content-revision)
     123           32 :     event-id         (assoc :event_id [:cast event-id :uuid])
     124           14 :     template-id      (assoc :template_id [:cast template-id :uuid])))
     125              : 
     126              : 
     127            4 : (defrecord
     128              :   PostgresTelegramChatMessageRepository
     129              :   [ds]
     130              :   TelegramChatMessagePostgresRepository
     131              : 
     132              :   (record!
     133              :    [_ msg]
     134            4 :    (try
     135           16 :      (let [row    (msg->row msg)
     136           32 :            query  {:insert-into :telegram_chat_messages
     137            8 :                    :values      [row]
     138           12 :                    :on-conflict [:chat-id :message-id]
     139              :                    :do-nothing  true
     140            8 :                    :returning   [:*]}
     141            4 :            result (->>
     142           12 :                     (sql/format query)
     143           12 :                     (jdbc/execute! ds)
     144            4 :                     first)
     145           18 :            result (or
     146            4 :                    result
     147              :                    (->>
     148            4 :                      (sql/format
     149           12 :                       {:select [:*]
     150            4 :                        :from   [:telegram_chat_messages]
     151            4 :                        :where  [:and
     152           12 :                                 [:= :chat-id (:chat_id row)]
     153           12 :                                 [:= :message-id (:message_id row)]]})
     154            6 :                      (jdbc/execute! ds)
     155            2 :                      first))]
     156           20 :        (either/right (row->msg result)))
     157              :      (catch Exception e
     158            0 :        (either/left
     159            0 :         (utils.errors/build-error
     160              :          :postgres
     161            0 :          {:message (.getMessage e)
     162            0 :           :context {:table :telegram_chat_messages
     163              :                     :op    :record}})))))
     164              : 
     165              :   (find-undeleted-for-event
     166              :    [_ event-id]
     167            3 :    (->>
     168            6 :      (sql/format
     169            6 :       (message-query
     170           45 :        {:where [:and [:= :tcm.event-id [:cast event-id :uuid]] [:is :tcm.deleted-at nil]]}))
     171            9 :      (jdbc/execute! ds)
     172            6 :      (mapv row->msg)))
     173              : 
     174              :   (find-undeleted-for-template
     175              :    [_ template-id]
     176            0 :    (->>
     177            0 :      (sql/format
     178            0 :       (message-query
     179            0 :        {:where [:and [:= :tcm.template-id [:cast template-id :uuid]] [:is :tcm.deleted-at nil]]}))
     180            0 :      (jdbc/execute! ds)
     181            0 :      (mapv row->msg)))
     182              : 
     183              :   (find-by-event-id
     184              :    [_ event-id]
     185            3 :    (->>
     186            6 :      (sql/format
     187            6 :       (message-query
     188           30 :        {:where    [:= :tcm.event-id [:cast event-id :uuid]]
     189           12 :         :order-by [[:tcm.created-datetime :asc]]}))
     190            9 :      (jdbc/execute! ds)
     191            6 :      (mapv row->msg)))
     192              : 
     193              :   (find-by-event-ids
     194              :    [_ event-ids]
     195            0 :    (if (empty? event-ids)
     196            0 :      []
     197            0 :      (->>
     198            0 :        (sql/format
     199            0 :         (message-query
     200            0 :          {:where    [:in :tcm.event-id (mapv #(vector :cast % :uuid) event-ids)]
     201            0 :           :order-by [[:tcm.created-datetime :asc]]}))
     202            0 :        (jdbc/execute! ds)
     203            0 :        (mapv row->msg))))
     204              : 
     205              :   (find-by-template-id
     206              :    [_ template-id]
     207            1 :    (->>
     208            2 :      (sql/format
     209            2 :       (message-query
     210           10 :        {:where    [:= :tcm.template-id [:cast template-id :uuid]]
     211            4 :         :order-by [[:tcm.created-datetime :asc]]}))
     212            3 :      (jdbc/execute! ds)
     213            2 :      (mapv row->msg)))
     214              : 
     215              :   (find-by-template-ids
     216              :    [_ template-ids]
     217            0 :    (if (empty? template-ids)
     218            0 :      []
     219            0 :      (->>
     220            0 :        (sql/format
     221            0 :         (message-query
     222            0 :          {:where    [:in :tcm.template-id (mapv #(vector :cast % :uuid) template-ids)]
     223            0 :           :order-by [[:tcm.created-datetime :asc]]}))
     224            0 :        (jdbc/execute! ds)
     225            0 :        (mapv row->msg))))
     226              : 
     227              :   (mark-deleted!
     228              :    [_ uuids]
     229            4 :    (try
     230           20 :      (when (seq uuids)
     231            8 :        (jdbc/execute!
     232            4 :         ds
     233            8 :         (sql/format
     234           20 :          {:update :telegram_chat_messages
     235           16 :           :set    {:deleted_at [:now]}
     236           72 :           :where  [:and [:in :uuid (mapv #(vector :cast % :uuid) uuids)] [:is :deleted-at nil]]})))
     237           12 :      (either/right nil)
     238              :      (catch Exception e
     239            0 :        (either/left
     240            0 :         (utils.errors/build-error
     241              :          :postgres
     242            0 :          {:message (.getMessage e)
     243            0 :           :context {:table :telegram_chat_messages
     244              :                     :op    :mark-deleted}}))))))
     245              : 
     246              : 
     247            4 : (defn make-repository
     248              :  "Creates a PostgresTelegramChatMessageRepository."
     249              :  [ds]
     250           12 :  (->PostgresTelegramChatMessageRepository ds))
     251              : 
     252              : 
     253            4 : (defn update-post!
     254              :  "Persist an in-place edit without changing its original creation timestamp."
     255           24 :  ([repo chat-id message-id text kind] (update-post! repo chat-id message-id text kind nil))
     256              :  ([repo chat-id message-id text kind content-revision]
     257            6 :   (jdbc/execute!
     258            9 :    (:ds repo)
     259            6 :    (sql/format
     260           15 :     {:update :telegram-chat-messages
     261           15 :      :set    {:message-text text
     262            3 :               :kind         kind
     263            3 :               :content-revision content-revision}
     264           30 :      :where  [:and [:= :chat-id chat-id] [:= :message-id message-id]]}))))
     265              : 
     266              : 
     267            4 : (defn event-ids-with-main-posts
     268              :  "Events of a template that still have an undeleted main post in the given chat/thread."
     269              :  [repo template-id chat-id thread-id]
     270            2 :  (->>
     271            4 :    (sql/format
     272           18 :     {:select-distinct [[:tcm.event-id :event-id]]
     273            8 :      :from  [[:telegram-chat-messages :tcm]]
     274           16 :      :join  [[:events :e] [:= :e.uuid :tcm.event-id]]
     275            4 :      :where [:and
     276           14 :              [:= :e.template-id [:cast template-id :uuid]]
     277           14 :              [:not-in :e.source ["psa" "fsu" "esf"]]
     278            8 :              [:= :tcm.chat-id chat-id]
     279           16 :              [:= :tcm.thread-id (or thread-id -1)]
     280            8 :              [:is :tcm.deleted-at nil]
     281           12 :              [:in :tcm.kind ["participants_post" "draws_post"]]]})
     282           10 :    (jdbc/execute! (:ds repo))
     283           18 :    (mapv #(str (:event-id (utils.db/unqualify-keys %))))))
        

Generated by: LCOV version 2.0-1