From b51611d4d6b09dbb405954cc82f93472f87838d9 Mon Sep 17 00:00:00 2001 From: loganlinn Date: Thu, 6 Aug 2015 11:03:06 -0700 Subject: [PATCH] Add fn-handler for CASE statement --- src/honeysql/format.clj | 10 ++++++++++ test/honeysql/core_test.clj | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/honeysql/format.clj b/src/honeysql/format.clj index 590bfc7..c879fa7 100644 --- a/src/honeysql/format.clj +++ b/src/honeysql/format.clj @@ -523,3 +523,13 @@ (defmethod format-clause :union-all [[_ maps] _] (string/join " UNION ALL " (map to-sql maps))) + +(defmethod fn-handler "case" [_ & clauses] + (str "CASE " + (space-join + (for [[condition result] (partition 2 clauses)] + (if (= :else condition) + (str "ELSE " (to-sql result)) + (let [pred (format-predicate* condition)] + (str "WHEN " pred " THEN " (to-sql result)))))) + " END")) diff --git a/test/honeysql/core_test.clj b/test/honeysql/core_test.clj index cea3b31..12b55d9 100644 --- a/test/honeysql/core_test.clj +++ b/test/honeysql/core_test.clj @@ -127,3 +127,29 @@ :from [:customers] :where [:in :id :?ids]} {:ids values}))))))) + +(deftest test-case + (is (= ["SELECT CASE WHEN foo < 0 THEN -1 WHEN (foo > 0 AND (foo mod 2) = 0) THEN (foo / 2) ELSE 0 END FROM bar"] + (sql/format + {:select [(sql/call + :case + [:< :foo 0] -1 + [:and [:> :foo 0] [:= (sql/call :mod :foo 2) 0]] (sql/call :/ :foo 2) + :else 0)] + :from [:bar]}))) + (let [param1 1 + param2 2 + param3 "three"] + (is (= ["SELECT CASE WHEN foo = ? THEN 0 WHEN foo = bar THEN ? WHEN bar = 0 THEN (bar * ?) ELSE ? END FROM baz" + param1 param2 param3 "param4"] + (sql/format + {:select [(sql/call + :case + [:= :foo :?param1] 0 + [:= :foo :bar] (sql/param :param2) + [:= :bar 0] (sql/call :* :bar :?param3) + :else "param4")] + :from [:baz]} + {:param1 param1 + :param2 param2 + :param3 param3})))))