简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM