kit-clj / kit

Lightweight, modular framework for scalable web development in Clojure
https://kit-clj.github.io/
MIT License
463 stars 43 forks source link

how to run this hugsql snip #108

Closed vinurs closed 11 months ago

vinurs commented 11 months ago

from https://www.hugsql.org/using-hugsql/composability/snippets

-- :snip select-snip
select :i*:cols

-- :snip from-snip
from :i*:tables

-- :snip where-snip
where :snip*:cond

-- :snip cond-snip
-- We could come up with something
-- quite elaborate here with some custom
-- parameter types that convert := to =, etc.,
-- Examples:
-- {:conj "and" :cond ["id" "=" 1]}
-- OR
-- {:conj "or" :cond ["id" "=" 1]}
-- note that :conj can be "", too
:sql:conj :i:cond.0 :sql:cond.1 :v:cond.2

-- :name snip-query :? :*
:snip:select
:snip:from
--~ (when (:where params) ":snip:where")

then run the snip-query

(snip-query
  db
  {:select (select-snip {:cols ["id","name"]})
   :from (from-snip {:tables ["test"]})
   :where (where-snip {:cond [(cond-snip {:conj "" :cond ["id" "=" 1]})
                              (cond-snip {:conj "or" :cond ["id" "=" 2]})]})})

but in this framework, how should i do to run snip-query?

(query-fn :snip-query {})

but the select-snip from-snip how to

yogthos commented 11 months ago

So, what happens with the query-fn is that it uses bind-connection-map from conman to initialize the queries and snippets, you can see this here https://github.com/kit-clj/kit/blob/master/libs/kit-sql-conman/src/kit/edge/db/sql/conman.clj

and the helper functions come from conman here https://github.com/luminus-framework/conman/blob/78eb55c992b74095bf63a3d67b0c2a27d4d620e7/src/conman/core.clj#L119

vinurs commented 11 months ago

thanks for ur help in system.edn i defined a snip-fn

:db.sql/snip-fn
 {:conn #ig/ref :db.sql/connection
  :options {}
  :filenames ["sql/pg/snippets.sql"]}

then

(defmethod ig/init-key :db.sql/snip-fn
  [_ {:keys [conn options filename filenames]
      :or   {options {}}}]
  (let [filenames (or filenames [filename])
        snips (apply conman/bind-connection-map conn options filenames)]
    (fn [snip params]
      (conman/snip snips snip params))))

so now can call it as following

(query-fn :snip-query
            {:select (snip-fn :select-snip {:cols ["id","nickname"]})
             :from (snip-fn :from-snip {:tables ["user_profile"]})
             :where (snip-fn :where-snip
                             {:cond [(snip-fn :cond-snip {:conj "" :cond ["id" "=" 10001]})
                                     (snip-fn :cond-snip {:conj "or" :cond ["id" "=" 10002]})]})})