hugsql
hugsql copied to clipboard
Example of how to do query.sql code reload
Hello,
Hugsql seems amazing. Pretty new to clojure, and just can't seem to find any resource out there on how to reload the query.sql.
I am using component for my project and have core reload with 'clojure.tools.namespace.repl' with set-refresh-dirs.
Guessing that the workflow can't be restart repl. Would be really helpful if you could share a example of a reload flow Thank you :)
Here's the solution I came up with. It's pretty dirty, but seems to work ok. I'd love to know of a better way though.
(ns my.app.db.queries
(:require [my.app.vendor.hugsql.core :as hugsql]
[com.stuartsierra.component :as component]
[clojure.set :as set]))
(def this-ns *ns*)
(def queries-file "queries/app.sql")
;; DB fns need to be defined twice, once here to ensure they exist when refreshing
;; the namespace.
(hugsql/def-db-fns queries-file)
;; And once here as a component, so that changes to the file will still be picked up.
(defrecord PostgresQueries [resource-path]
component/Lifecycle
(start [this]
(hugsql/def-db-fns resource-path {:ns this-ns})
this)
(stop [this]
this))
(defn new-queries []
(map->PostgresQueries {:resource-path queries-file}))
I got around this by using map-of-db-fns within the component, passing in my db connection with use-component, and appending a function which takes a keyword and (maybe) options, and calls the function using the db spec:
(defrecord Queries [resource-path hikari-cp]
component/Lifecycle
(start [this]
(let [map-of-fns (hugsql/map-of-db-fns queries-file)]
(assoc this
:fns map-of-fns
:query-fn
(fn query-fn
([kw]
(query-fn kw {}))
([kw opts]
((get-in map-of-fns [kw :fn])
(:db-spec hikari-cp)
opts))))))
(stop [this]
(-> this
(dissoc :query-fn)
(dissoc :fns))))
I submitted a patch to tools.namespace which would allow reloads to work. In your namespace, you'd be able to track external files as part of your namespace changing.
(ns my-ns
{:clojure.tools.namespace.files/filedeps #{"queries/app.sql"})
(def queries-file "queries/app.sql")
(hugsql/def-db-fns queries-file)
It has not been looked at yet though 🤞 https://dev.clojure.org/jira/browse/TNS-48
Hey folks I have a fork with TNS-48 applied.
There's some instructions in the README (it should work as a drop-in replacement for existing tools.namespace 😁)
👉 https://github.com/rymndhng/tools.namespace 🤜 https://github.com/rymndhng/tools.namespace#file-support
I'm looking for feedback to see if this is something valuable to y'all 😁
I also got it working using: https://github.com/weavejester/ns-tracker with the example under "Declaring Dependencies to Static Resources"