match all key/val pairs

120 views Asked by At

Original query:

-- :name select*-list
-- :command :query
-- :result :raw
-- :doc Select all lists.
-- parameters()
SELECT * FROM list;

I want to pass in arbitrary key/val pairs and get matching results. For example:

(select*-list db-spec {:name "Fruit" :type "Foo"})

should result in:

SELECT * FROM list 
WHERE name = 'Fruit'
AND type = 'Foo';

I can think of a few ugly ways to accomplish this but it's likely I'm overlooking some nice way to do this.

2

There are 2 answers

0
Ivan Grishaev On

JDBC has some great shortcuts out from the box. One of them is find-by-keys. It does exactly what you want: takes a map of key/value pairs and composes a set of WHERE clauses connected with AND:

(jdbc/find-by-keys db-spec :users {:name "John" :age 42 :city "Chita"})

will turn out to

select from users
where
  name = 'John'
  and age = 42
  and city = 'Chita';
0
Alan Thompson On

Here is an example java-jdbc.sql

(require '[java-jdbc.sql :as sql])

(jdbc/query db-spec
  (sql/select * :fruit (sql/where {:appearance "ripe"})))
;; -> ({:grade 8.4, :unit "carton", :cost 12, :appearance "ripe", :name "Plum"})

Please see: