Improve type formatting logic in :cast function

This commit is contained in:
Youngil Choi 2022-11-20 06:51:43 +09:00
parent 562b20634a
commit a87fa0c9ab
4 changed files with 17 additions and 6 deletions

View file

@ -702,7 +702,7 @@ have a lot of function calls needed in code:
(sql/format {:pretty true})) (sql/format {:pretty true}))
=> [" => ["
INSERT INTO sample 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] 0.291 32.621 4325]
``` ```

View file

@ -79,7 +79,7 @@ that produces a SQL type:
```clojure ```clojure
(sql/format-expr [:cast :a :int]) (sql/format-expr [:cast :a :int])
;;=> ["CAST(a AS int)"] ;;=> ["CAST(a AS INT)"]
``` ```
## composite ## composite

View file

@ -1426,7 +1426,9 @@
:cast :cast
(fn [_ [x type]] (fn [_ [x type]]
(let [[sql & params] (format-expr x) (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' ")")] (-> [(str "CAST(" sql " AS " sql' ")")]
(into params) (into params)
(into params')))) (into params'))))

View file

@ -249,10 +249,19 @@
(sql/format)))))) (sql/format))))))
(deftest test-cast (deftest test-cast
(is (= ["SELECT foo, CAST(bar AS integer)"] (is (= ["SELECT foo, CAST(bar AS INTEGER)"]
(sql/format {:select [:foo [[:cast :bar :integer]]]}))) (sql/format {:select [:foo [[:cast :bar :integer]]]})))
(is (= ["SELECT foo, CAST(bar AS integer)"] (is (= ["SELECT foo, CAST(bar AS INTEGER)"]
(sql/format {:select [:foo [[:cast :bar '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 (deftest test-value
(is (= ["INSERT INTO foo (bar) VALUES (?)" {:baz "my-val"}] (is (= ["INSERT INTO foo (bar) VALUES (?)" {:baz "my-val"}]