Fork me on GitHub
#sql
<
2021-03-19
>
orestis14:03:19

A question about honeysql 1.0 -> I use a threading macro quite a lot to do things like:

(-> (h/select ...)
    (h/from ...)
    (h/left-join ...))
I would like to conditionally add a where clause without changing everything into a cond->, is there a clever trick I'm missing?

orestis14:03:16

I've came up with

(defn- cond-query [query c f]
  (if-not c
   query
   (f query)))

orestis14:03:00

Which allows me to thread into the first expression something like

(cond-query (not (string/blank? search))
                #(h/where % [:like :u.title (str "%" search)]))
But it's not ideal in terms of readability.

orestis14:03:27

I guess I'm used to be able to just in throw a nil when merging dictionaries, which is what honeysql does behind the scenes...

orestis14:03:36

Ohhh (h/where nil) works

dharrigan15:03:39

I have lots of these going on...

dharrigan15:03:42

(where
         [:= :poi.tenant-id tenant-id]
         (when poi-id [:= :poi-id poi-id])
         (when uuid [:= :poi.uuid uuid])

dharrigan15:03:08

first one is mandatory, rest optional

seancorfield16:03:11

@orestis You can either drop a cond-> into a -> pipeline or, as you’ve discovered, just let the condition eval to nil. That was added some time ago and should work the same on V2.

seancorfield16:03:15

I kind of like having embedded cond-> inside -> because it makes the condition explicit at the top level (and works with all helpers — the nil trick only works with h/where).

orestis18:03:30

Oh that's true about cond-> thanks @seancorfield

orestis18:03:10

I'm back writing SQL queries so I would hope to take honeysql v2 for a spin. Although we're also evaluating Penkala and Walkable as additions/alternatives.

seancorfield18:03:26

Walkable looks like quite a bit of work to set up schemas-in-code so I haven’t tried that yet. Hadn’t heard of Penkala.

seancorfield18:03:03

Ah, Penkala also relies on schema-in-code. I’m not fond of that approach myself. I don’t like having to duplicate in code stuff that’s already encoded in the database. But then I’m also happy grubbing around down at the SQL level anyway.

seancorfield18:03:19

Good to see more options for folks who want something higher-level.