Search code examples
clojure

select-keys with default value


Is there a function like select-keys but with default values for missing keys?

The reason I'm asking is that I'm using korma to query a database. I found a bug where using select-keys is not intuitive when it has no matches.

Example:

(delete t
  (where
    (select-keys {:k1 "v1" :k2 "v2"} [:k1])))

Same as:

(delete t
  (where {:k1 "v1"}))

Which translates through korma to something like:

delete from t where k1='v1'

Nice. select-keys creates just the query map I want.

But:

(delete t
  (where
    (select-keys {:k2 "v2"} [:k1])))

Same as:

(delete t
  (where {}))

Which translates through korma to something like:

delete from t

Which will delete my entire table t :(

I thought about using (merge defaults (select-keys ...)) or create a function select-keys-with-default, but I felt that like (get m :blah "default") there should probably be something built-in that I'm missing.

Browsing through the docs, or related functions offered there, didn't show anything useful out-of-the-box.


Solution

  • You probably don't want to execute a query at all when the selection is empty. So something like this would probably do:

    (when-let [selection (not-empty (select-keys ...))]
      (delete t (where selection)))