From a87fa0c9ab52a8e15bd284715dbb84257c691793 Mon Sep 17 00:00:00 2001 From: Youngil Choi Date: Sun, 20 Nov 2022 06:51:43 +0900 Subject: [PATCH] Improve type formatting logic in :cast function --- README.md | 2 +- doc/special-syntax.md | 2 +- src/honey/sql.cljc | 4 +++- test/honey/sql/helpers_test.cljc | 15 ++++++++++++--- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ed191cd..edb715d 100644 --- a/README.md +++ b/README.md @@ -702,7 +702,7 @@ have a lot of function calls needed in code: (sql/format {:pretty true})) => [" INSERT INTO sample -(location) VALUES (ST_SETSRID(ST_MAKEPOINT(?, ?), CAST(? AS integer))) +(location) VALUES (ST_SETSRID(ST_MAKEPOINT(?, ?), CAST(? AS INTEGER))) " 0.291 32.621 4325] ``` diff --git a/doc/special-syntax.md b/doc/special-syntax.md index 7acae94..d5affe6 100644 --- a/doc/special-syntax.md +++ b/doc/special-syntax.md @@ -79,7 +79,7 @@ that produces a SQL type: ```clojure (sql/format-expr [:cast :a :int]) -;;=> ["CAST(a AS int)"] +;;=> ["CAST(a AS INT)"] ``` ## composite diff --git a/src/honey/sql.cljc b/src/honey/sql.cljc index 76a6717..cbaea22 100644 --- a/src/honey/sql.cljc +++ b/src/honey/sql.cljc @@ -1426,7 +1426,9 @@ :cast (fn [_ [x type]] (let [[sql & params] (format-expr x) - [sql' & params'] (format-expr type)] + [sql' & params'] (if (ident? type) + [(sql-kw type)] + (format-expr type))] (-> [(str "CAST(" sql " AS " sql' ")")] (into params) (into params')))) diff --git a/test/honey/sql/helpers_test.cljc b/test/honey/sql/helpers_test.cljc index a512556..ec2af97 100644 --- a/test/honey/sql/helpers_test.cljc +++ b/test/honey/sql/helpers_test.cljc @@ -249,10 +249,19 @@ (sql/format)))))) (deftest test-cast - (is (= ["SELECT foo, CAST(bar AS integer)"] + (is (= ["SELECT foo, CAST(bar AS INTEGER)"] (sql/format {:select [:foo [[:cast :bar :integer]]]}))) - (is (= ["SELECT foo, CAST(bar AS integer)"] - (sql/format {:select [:foo [[:cast :bar 'integer]]]})))) + (is (= ["SELECT foo, CAST(bar AS INTEGER)"] + (sql/format {:select [:foo [[:cast :bar 'integer]]]}))) + (is (= ["SELECT foo, CAST(bar AS DOUBLE PRECISION)"] ;; Postgres example + (sql/format {:select [:foo [[:cast :bar :double-precision]]]}))) + (is (= ["SELECT \"foo\", CAST(\"bar\" AS INTEGER)"] + (sql/format {:select [:foo [[:cast :bar :integer]]]} {:quoted true}))) + (is (= ["SELECT `foo`, CAST(`bar` AS INTEGER)"] + (sql/format {:select [:foo [[:cast :bar :integer]]]} {:dialect :mysql}))) + (is (= ["SELECT `foo`, CAST(`bar` AS CHAR(10))"] + (sql/format {:select [:foo [[:cast :bar [:char 10]]]]} {:dialect :mysql + :inline true})))) (deftest test-value (is (= ["INSERT INTO foo (bar) VALUES (?)" {:baz "my-val"}]