sql

All things SQL and JDBC...
orestis 2021-03-19T14:56:19.032300Z

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?

orestis 2021-03-19T14:57:16.032600Z

I've came up with

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

orestis 2021-03-19T14:58:00.033200Z

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.

orestis 2021-03-19T14:58:27.033800Z

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...

orestis 2021-03-19T14:59:36.034100Z

Ohhh (h/where nil) works

dharrigan 2021-03-19T15:32:39.034300Z

I have lots of these going on...

dharrigan 2021-03-19T15:32:42.034500Z

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

dharrigan 2021-03-19T15:33:08.034900Z

first one is mandatory, rest optional

seancorfield 2021-03-19T16:49:11.035900Z

@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.

seancorfield 2021-03-19T16:50:15.036900Z

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).

orestis 2021-03-19T18:34:30.037200Z

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

orestis 2021-03-19T18:35:10.037900Z

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.

seancorfield 2021-03-19T18:36:26.038600Z

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.

seancorfield 2021-03-19T18:40:03.039800Z

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.

seancorfield 2021-03-19T18:40:19.040200Z

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