From 9f20ade0fe867a0f0157faa2dd1b323b2cb83b19 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 25 Sep 2020 15:31:11 -0700 Subject: [PATCH] Fix is/not null generation --- src/honey/sql.cljc | 30 +++++++++++++++++++----------- test/honey/sql_test.cljc | 15 +++++++++++++++ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/honey/sql.cljc b/src/honey/sql.cljc index f0901ae..d446b3c 100644 --- a/src/honey/sql.cljc +++ b/src/honey/sql.cljc @@ -463,17 +463,24 @@ (let [op (first x)] (if (keyword? op) (cond (infix-ops op) - (let [[_ a b] x + (let [[_ a b] x [s1 & p1] (format-expr a {:nested? true}) - [s2 & p2] (format-expr b {:nested? true})] - (-> (str s1 " " - (sql-kw (get infix-aliases op op)) - " " s2) - (cond-> nested? - (as-> s (str "(" s ")"))) - (vector) - (into p1) - (into p2))) + [s2 & p2] (format-expr b {:nested? true}) + op (get infix-aliases op op)] + (if (and (#{:= :<>} op) (or (nil? a) (nil? b))) + (-> (str (if (nil? a) + (if (nil? b) "NULL" s2) + s1) + (if (= := op) " IS NULL" " IS NOT NULL")) + (cond-> nested? + (as-> s (str "(" s ")"))) + (vector)) + (-> (str s1 " " (sql-kw op) " " s2) + (cond-> nested? + (as-> s (str "(" s ")"))) + (vector) + (into p1) + (into p2)))) (special-syntax op) (let [formatter (special-syntax op)] (formatter (rest x))) @@ -573,6 +580,7 @@ (format {:select [:*] :from [:table] :order-by [[[:date :expiry] :desc] :bar]} {}) (format {:select [:*] :from [:table] :where [:< [:date_add :expiry [:interval 30 :days]] [:now]]} {}) (format-expr [:interval 30 :days]) - (format {:select [:*] :from [:table] :where [:= :id 1]} {:dialect :mysql}) + (format {:select [:*] :from [:table] :where [:= :id (int 1)]} {:dialect :mysql}) + (map fn? (format {:select [:*] :from [:table] :where [:= :id (with-meta (constantly 42) {:foo true})]} {:dialect :mysql})) (format {:select [:*] :from [:table] :where [:in :id [1 2 3 4]]} {}) ,) diff --git a/test/honey/sql_test.cljc b/test/honey/sql_test.cljc index 90c5844..f843c76 100644 --- a/test/honey/sql_test.cljc +++ b/test/honey/sql_test.cljc @@ -12,6 +12,21 @@ {:dialect :mysql})))) (deftest expr-tests + (is (= ["id IS NULL"] + (sut/format-expr [:= :id nil]))) + (is (= ["id IS NULL"] + (sut/format-expr [:is :id nil]))) + (is (= ["id IS NOT NULL"] + (sut/format-expr [:<> :id nil]))) + (is (= ["id IS NOT NULL"] + (sut/format-expr [:!= :id nil]))) + (is (= ["id IS NOT NULL"] + (sut/format-expr [:is-not :id nil]))) + ;; degenerate cases: + (is (= ["NULL IS NULL"] + (sut/format-expr [:= nil nil]))) + (is (= ["NULL IS NOT NULL"] + (sut/format-expr [:<> nil nil]))) (is (= ["id = ?" 1] (sut/format-expr [:= :id 1]))) (is (= ["id + ?" 1]