Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve type formatting logic in :cast function #443

Merged
merged 1 commit into from
Nov 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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