Fix is/not null generation

This commit is contained in:
Sean Corfield 2020-09-25 15:31:11 -07:00
parent 1c7e08bb82
commit 9f20ade0fe
2 changed files with 34 additions and 11 deletions

View file

@ -465,15 +465,22 @@
(cond (infix-ops op) (cond (infix-ops op)
(let [[_ a b] x (let [[_ a b] x
[s1 & p1] (format-expr a {:nested? true}) [s1 & p1] (format-expr a {:nested? true})
[s2 & p2] (format-expr b {:nested? true})] [s2 & p2] (format-expr b {:nested? true})
(-> (str s1 " " op (get infix-aliases op op)]
(sql-kw (get infix-aliases op op)) (if (and (#{:= :<>} op) (or (nil? a) (nil? b)))
" " s2) (-> (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? (cond-> nested?
(as-> s (str "(" s ")"))) (as-> s (str "(" s ")")))
(vector) (vector)
(into p1) (into p1)
(into p2))) (into p2))))
(special-syntax op) (special-syntax op)
(let [formatter (special-syntax op)] (let [formatter (special-syntax op)]
(formatter (rest x))) (formatter (rest x)))
@ -573,6 +580,7 @@
(format {:select [:*] :from [:table] :order-by [[[:date :expiry] :desc] :bar]} {}) (format {:select [:*] :from [:table] :order-by [[[:date :expiry] :desc] :bar]} {})
(format {:select [:*] :from [:table] :where [:< [:date_add :expiry [:interval 30 :days]] [:now]]} {}) (format {:select [:*] :from [:table] :where [:< [:date_add :expiry [:interval 30 :days]] [:now]]} {})
(format-expr [:interval 30 :days]) (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]]} {}) (format {:select [:*] :from [:table] :where [:in :id [1 2 3 4]]} {})
,) ,)

View file

@ -12,6 +12,21 @@
{:dialect :mysql})))) {:dialect :mysql}))))
(deftest expr-tests (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] (is (= ["id = ?" 1]
(sut/format-expr [:= :id 1]))) (sut/format-expr [:= :id 1])))
(is (= ["id + ?" 1] (is (= ["id + ?" 1]