Skip to content

Instantly share code, notes, and snippets.

@ashafa
Created February 16, 2009 00:35
Show Gist options
  • Save ashafa/64924 to your computer and use it in GitHub Desktop.
Save ashafa/64924 to your computer and use it in GitHub Desktop.
(ns clj-record.query
(:require [clojure.contrib.str-utils :as str-utils]))
(defn- clause-and-parameters [join-with values]
[(str-utils/str-join join-with (reduce (fn [v1 v2] (conj v1 (if (nil? v2) "NULL" "?"))) [] values)) (filter (complement nil?) values)])
(defn between [value1 value2]
(fn [attribute]
(let [[clause parameters] (clause-and-parameters " AND " [value1 value2])]
[(str (name attribute) " BETWEEN " clause) parameters])))
(defn in [& values]
(fn [attribute]
(let [[clause parameters] (clause-and-parameters ", " values)]
[(str (name attribute) " IN (" clause ")") parameters])))
(defn like [value]
(fn [attribute]
(let [[clause parameters] (clause-and-parameters "" [value])]
[(str (name attribute) " LIKE " clause) parameters])))
;; to-conditions tests
["a BETWEEN ? AND ?" 1 3] {:a (query/between 1 3)}
["a IN (?, ?, NULL, ?)" "foo" "bar" "baz"] {:a (query/in "foo" "bar" nil "baz")}
["a LIKE ?" "h%"] {:a (query/like "h%")}
;; An associated test...
(defdbtest find-records-using-between
(let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors" :grade 90}))
foyoto (manufacturer/create (valid-manufacturer-with {:name "Foyoto Auto" :grade 78}))
gmb (manufacturer/create (valid-manufacturer-with {:name "GMB Motors" :grade 89}))
ghysler (manufacturer/create (valid-manufacturer-with {:name "Ghysler Inc" :grade 59}))
merledas (manufacturer/create (valid-manufacturer-with {:name "Merledas Automotive" :grade 39}))]
(let [records (manufacturer/find-records {:grade (query/between 40 80)})]
(is (or (= [ghysler foyoto] records) (= [foyoto ghysler] records))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment