From 2abe12800829212793dc21c5fa26a974d2665b65 Mon Sep 17 00:00:00 2001 From: Juvenn Woo Date: Fri, 9 Mar 2018 11:54:14 +0800 Subject: [PATCH] Support register customized parameterizer --- src/honeysql/format.cljc | 11 +++++++++++ test/honeysql/format_test.cljc | 16 +++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/honeysql/format.cljc b/src/honeysql/format.cljc index 78eddf7..e17f577 100644 --- a/src/honeysql/format.cljc +++ b/src/honeysql/format.cljc @@ -56,6 +56,17 @@ :jdbc (constantly "?") :none #(str (last @*params*))}) +(defn register-parameterizer + "Register f as a customized parameterizer. + E.g.: + (register-parameterizer :single-quote #(str \"'\" % \"'\")) + (format sql-map :parameterizer :single-quote)" + [k f] + (alter-var-root + #'parameterizers + (fn [m] + (assoc m k #(f (last @*params*)))))) + (def ^:dynamic *quote-identifier-fn* nil) (def ^:dynamic *parameterizer* nil) diff --git a/test/honeysql/format_test.cljc b/test/honeysql/format_test.cljc index 84d7fc5..2976fce 100644 --- a/test/honeysql/format_test.cljc +++ b/test/honeysql/format_test.cljc @@ -4,7 +4,8 @@ :cljs [cljs.test :refer-macros]) [deftest testing is are]] [honeysql.types :as sql] [honeysql.format :refer - [*allow-dashed-names?* quote-identifier format-clause format]])) + [*allow-dashed-names?* quote-identifier format-clause format + register-parameterizer]])) (deftest test-quote (are @@ -174,3 +175,16 @@ (is (= (format {:where [:and [:= :foo "foo"] [:= :bar "bar"] nil]} :parameterizer :postgresql) ["WHERE (foo = $1 AND bar = $2)" "foo" "bar"])))) + +(register-parameterizer :single-quote #(str \' % \')) +(register-parameterizer :mysql-fill (constantly "?")) + +(deftest customized-parameterizer + (testing "should fill param with single quote" + (is (= (format {:where [:and [:= :foo "foo"] [:= :bar "bar"] nil]} + :parameterizer :single-quote) + ["WHERE (foo = 'foo' AND bar = 'bar')" "foo" "bar"]))) + (testing "should fill param with ?" + (is (= (format {:where [:and [:= :foo "foo"] [:= :bar "bar"] nil]} + :parameterizer :mysql-fill) + ["WHERE (foo = ? AND bar = ?)" "foo" "bar"]))))