Fork me on GitHub
#sql
<
2021-05-12
>
Michaël Salihi14:05:35

Hi! If I want to compose sql queries with some conditions. I can use str to concatenate like that but I'm sure this isn't the right way to do:

(defn retrieve-all-users-and-filter [filters]
  (jdbc/execute! db [(str "SELECT id, first_name || ' ' || last_name as name, email, owner FROM users"
                          (when filters " WHERE first_name LIKE ?")
                          " ORDER BY last_name ASC, first_name ASC ") (when filters (str "%" (:search filters) "%"))]))
For more complex queries, is it interresting to use for eg. HoneySQL with Next.jdbc or is it a better solution that above with Next-jdbc? Any clue about that?

emccue15:05:03

@admin055 Best way i've found is to use honeysql

emccue15:05:39

(defn retrieve-all-users-query [filters]
  {:select [:id :first_name]
   :from [:users]
   :where [:and [:= 1 1]
                filters]})

👍 2
Michaël Salihi15:05:52

That turns out well, I am trying it. Thanks for your confirmation.

emccue15:05:21

(retrieve-all-users-query [:= :first_name "Joe])

Michaël Salihi15:05:47

I take this opportunity to ask, what is the equivalent for a pattern matching "%string%"

Michaël Salihi15:05:35

Ah I think you gave the answer above, I'll try that right now!

ghadi18:05:16

@admin055 @emccue Stu Halloway gave a talk last night called "Better Bugs Make Better Programs", and he advocated naming Datomic queries top-level in the same way as the SQL query a few messages above 👍:skin-tone-3:

👍 2
ghadi18:05:40

(he also advocated giving everything a docstring)

seancorfield18:05:00

I have clj-kondo flag any public var that doesn’t have a docstring. When I start writing a function, that’s usually the first thing I do:

(defn my-cool-function
  "Given <inputs>, <compute something> / return <something>.

  <more long form description about the function if needed>

  <any exceptional cases or caveats about usage>."
  [])
and then I add arguments based on the <inputs> I described, then I sketch out the function logic in a (comment ..) form and then “promote” it into the function body.

Michaël Salihi18:05:55

Always interresting to hear some others workflow, thanks.