Skip to content

Commit

Permalink
Allow where clause strings alongside edn clauses
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Walker committed Dec 21, 2018
1 parent 0f390cc commit b8c6d83
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 11 deletions.
25 changes: 16 additions & 9 deletions src/lighthouse/sql.clj
Original file line number Diff line number Diff line change
Expand Up @@ -249,13 +249,15 @@
:else "="))

(defn where-part [v]
(if (vector? v)
(let [[k op* val] v
parts (if (= '!= op*)
[(qualified-col-name k) (not-op val) (? val)]
[(qualified-col-name k) (op op*) (? op*)])]
(string/join " " parts))
(throw (Exception. (str "where requires vectors to work. You typed: " v)))))
(if (not (vector? v))
(throw (Exception. (str "where requires vectors to work. You typed: " v)))
(if (sql-vec? v)
(first v)
(let [[k op* val] v
parts (if (= '!= op*)
[(qualified-col-name k) (not-op val) (? val)]
[(qualified-col-name k) (op op*) (? op*)])]
(string/join " " parts)))))

(defn where-clause [[k v]]
(string/join (str " " (name k) " ")
Expand All @@ -279,13 +281,18 @@
(throw (Exception. (str "where only accepts and & or. You typed: " (if (nil? v) "nil" v))))
(map where-clause wv))))

(defn last-or-rest [v]
(if (sql-vec? v)
(rest v)
(last v)))

(defn where [v]
(if (sql-vec? v)
{:where (str "where " (first v))
:args (rest v)}
{:where (str "where " (string/join " and " (map #(wrap-str "()" %) (where-clauses v))))
:args (->> (filter vector? v)
(mapv last)
(mapv last-or-rest)
(filter some?)
(flat))}))

Expand Down Expand Up @@ -375,4 +382,4 @@
from-clause (or (:from m) (from-clause select-ks join-ks))
sql (->> (filter some? [select pull delete update update-set insert values from-clause joins where order offset limit group])
(string/join " "))]
(apply conj [sql] (concat update-set-args (filter some? args)))))
(apply conj [sql] (concat update-set-args (filter some? (flat args))))))
2 changes: 1 addition & 1 deletion src/lighthouse/transact.clj
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
pk (first (filter #(= "id" (name %)) (-> v first keys)))]
(concat
[:update table
:where [(name pk) (map #(get % pk) v)]]
:where [pk (mapv #(get % pk) v)]]
(conj (->> (mapcat identity v)
(distinct))
:set))))
Expand Down
2 changes: 1 addition & 1 deletion test/lighthouse/transact_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
(deftest update
(testing "valid update transaction"
(is (= (transact/update {:todo/name "new todo" :todo/id 1})
'(:update "todo" :where ["id" (1)] :set [:todo/name "new todo"] [:todo/id 1])))))
'(:update "todo" :where [:todo/id (1)] :set [:todo/name "new todo"] [:todo/id 1])))))

(deftest delete
(testing "valid delete transaction"
Expand Down

0 comments on commit b8c6d83

Please sign in to comment.