From 203296149f7d9d771639cef87555387f4ec07ffa Mon Sep 17 00:00:00 2001 From: Andy Chambers Date: Thu, 23 Apr 2015 23:44:19 -0700 Subject: [PATCH] Add support for exists --- .gitignore | 1 + CHANGES.md | 1 + src/honeysql/format.clj | 22 +++++++++++++++------- test/honeysql/format_test.clj | 10 ++++++++++ 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 2bfb42e..ec625cc 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ pom.xml* .lein-plugins .classpath .project +.nrepl-port bin diff --git a/CHANGES.md b/CHANGES.md index 8481996..26e96a0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ ## 0.5.3 In development +* Support exists syntax (@cddr) * Support locking selects (@dball) * Add sql array type and reader literal (@loganmhb) * Allow user to specify where in sort order NULLs fall (@mishok13) diff --git a/src/honeysql/format.clj b/src/honeysql/format.clj index 192e22b..8031484 100644 --- a/src/honeysql/format.clj +++ b/src/honeysql/format.clj @@ -350,13 +350,18 @@ (to-sql pred) (let [[op & args] pred op-name (name op)] - (if (= "not" op-name) - (str "NOT " (format-predicate* (first args))) - (if (#{"and" "or" "xor"} op-name) - (paren-wrap - (string/join (str " " (string/upper-case op-name) " ") - (map format-predicate* args))) - (to-sql (apply call pred))))))) + (case op-name + "not" (str "NOT " (format-predicate* (first args))) + + ("and" "or" "xor") + (paren-wrap + (string/join (str " " (string/upper-case op-name) " ") + (map format-predicate* args))) + + "exists" + (str "EXISTS " (to-sql (first args))) + + (to-sql (apply call pred)))))) (defmulti format-clause "Takes a map entry representing a clause and returns an SQL string" @@ -370,6 +375,9 @@ (defmethod format-clause :default [& _] "") +(defmethod format-clause :exists [[_ table-expr] _] + (str "EXISTS " (to-sql table-expr))) + (defmethod format-clause :select [[_ fields] sql-map] (str "SELECT " (when (:modifiers sql-map) diff --git a/test/honeysql/format_test.clj b/test/honeysql/format_test.clj index ce4a518..e0f8bca 100644 --- a/test/honeysql/format_test.clj +++ b/test/honeysql/format_test.clj @@ -34,6 +34,16 @@ (is (= (format-clause (first {:insert-into [[:foo [:a :b :c]] {:select [:d :e :f] :from [:baz]}]}) nil) "INSERT INTO foo (a, b, c) SELECT d, e, f FROM baz"))) +(deftest exists-test + (is (= (format {:exists {:select [:a] :from [:foo]}}) + ["EXISTS (SELECT a FROM foo)"])) + (is (= (format {:select [:id] + :from [:foo] + :where [:exists {:select [1] + :from [:bar] + :where :deleted}]}) + ["SELECT id FROM foo WHERE EXISTS (SELECT 1 FROM bar WHERE deleted)"]))) + (deftest array-test (is (= (format {:insert-into :foo :columns [:baz]