clojurekorma

Korma: or'ing dynamically generated where clauses


I have a set of dynamically generated parameters in a form of a map like

(def clauses {:apples 23 :plums 0 :bananas 7})

and I want to have it or'ed in a where statement, so it should become an equivalent of the Korma query:

(select fruit-shop
  (where (or {:apples 23}
             {:plums 0}
             {:bananas 7})))

Generating a list of maps is quite easy:

(map #(apply array-map %)
     (into [] clauses))

But one can't use (or statement applied to it, because it's handled at macro expansion time, before the clauses becomes bound to its value.

What statement should be used in such case?


Solution

  • After getting familiar with Korma source code, I have found korma.sql.fns/pred-or function that replaces or statements in where and having. So I wrote the following helper function that takes a map argument

    (require '[korma.sql.fns :refer [pred-or]])
    
    (defn or*
      [m]
      (apply pred-or
             (map #(apply array-map %)
                  (into [] m))))
    

    Given that, the intended query will look like this

    (select fruit-shop
      (where (or* clauses)))