Skip to content

Commit

Permalink
Merge pull request #443 from duddlf23/cast-type-format-fix
Browse files Browse the repository at this point in the history
Improve type formatting logic in :cast function
  • Loading branch information
seancorfield authored Nov 20, 2022
2 parents 562b206 + a87fa0c commit e4f0a5e
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
```
Expand Down
2 changes: 1 addition & 1 deletion doc/special-syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/honey/sql.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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'))))
Expand Down
15 changes: 12 additions & 3 deletions test/honey/sql/helpers_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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"}]
Expand Down

0 comments on commit e4f0a5e

Please sign in to comment.