LauJensen / clojureql

ClojureQL is superior SQL integration for Clojure
https://clojureql.sabrecms.com
Eclipse Public License 1.0
285 stars 39 forks source link

Handling optional predicates #101

Closed lynaghk closed 12 years ago

lynaghk commented 12 years ago

I caught myself throwing around a lot of if and str trying to handle optional predicates earlier today, but since that makes Danish and relational algebra-loving kittens mew sadly, I'm trying to find nicer ways to handle the situation.

Maybe the simplest would be to silently discard predicates with nil arguments:

    (-> (cql/table db :rates)
        (select (where (< :day nil)))
        (select (where (> :day "2006-01-01")))
        (project [:amount]))

    ;;(maybe becomes)=> SELECT rates.amount FROM rates WHERE (rates.day < 2006-01-01)

Currently the output is

    ;;=> SELECT rates.amount FROM rates WHERE (rates.day < 2006-01-01) AND (rates.day > ?)

where our non-nil predicate has slipped over to the wrong spot in the prepared statement. This would make the calling code very simple, at the risk of silently dropping predicates you actually want sometimes.

So far, I've been writing my ClojureQL code in the chained style:

(-> (cql/table db :rates)
    (select (where (< :day end_date)))
    (select (where (> :day start_date)))
    (project [:amount :day :check_in]))

and I guard against nil predicates using an ugly anonymous function:

(-> (cql/table db :rates)
    (#(if (nil? end_day) % (select % (where (< :day end_day)))))
    (select (where (> :day start_date)))
    (project [:amount :day :check_in]))

which I'm thinking about abstracting into a macro, but I'd like to get your opinions first. How do you all handle this issue? Should it be handled in the calling code or magically taken care of in the ClojureQL library code?

bendlas commented 12 years ago

Maybe select-if does what you want? https://github.com/LauJensen/clojureql/blob/master/src/clojureql/core.clj#L243

lynaghk commented 12 years ago

Yes, that is exactly what I want. I feel pretty silly having missed it, thanks for pointing it out.

bendlas commented 12 years ago

It's not yet documented, so no worries.