keyword syntax for sql calls
This commit is contained in:
parent
f9f2087163
commit
96ddbc18f4
3 changed files with 18 additions and 8 deletions
16
README.md
16
README.md
|
|
@ -91,17 +91,23 @@ Queries can be nested:
|
|||
=> ["SELECT * FROM foo WHERE (foo.a IN (SELECT a FROM bar))"]
|
||||
```
|
||||
|
||||
There are helper functions and data literals for field qualifiers, SQL function
|
||||
calls, raw SQL fragments, and named input parameters:
|
||||
Keywords that begin with `%` are interpreted as SQL function calls:
|
||||
|
||||
```clj
|
||||
(-> (select (sql/qualify :foo :a) (sql/call :count :*) (sql/raw "@var := foo.bar"))
|
||||
(-> (select :%count.*) (from :foo) sql/format)
|
||||
=> ["SELECT COUNT(*) FROM foo"]
|
||||
```
|
||||
|
||||
There are helper functions and data literals for SQL function calls, field qualifiers, raw SQL fragments, and named input parameters:
|
||||
|
||||
```clj
|
||||
(-> (select (sql/call :foo :bar) (sql/qualify :foo :a) (sql/raw "@var := foo.bar"))
|
||||
(from :foo)
|
||||
(where [:= :a (sql/param :baz)]))
|
||||
=> {:where [:= :a #sql/param :baz], :from (:foo), :select (#sql/call [:count :*] #sql/raw "@var := foo.bar")}
|
||||
=> {:where [:= :a #sql/param :baz], :from (:foo), :select (#sql/call [:foo :bar] :foo.a #sql/raw "@var := foo.bar")}
|
||||
|
||||
(sql/format *1 {:baz "BAZ"})
|
||||
=> ["SELECT COUNT(*), @var := foo.bar FROM foo WHERE a = ?" "BAZ"]
|
||||
=> ["SELECT FOO(bar), foo.a, @var := foo.bar FROM foo WHERE a = ?" "BAZ"]
|
||||
```
|
||||
|
||||
Here's a big, complicated query. Note that Honey SQL makes no attempt to verify that your queries make any sense. It merely renders surface syntax.
|
||||
|
|
|
|||
|
|
@ -154,7 +154,11 @@
|
|||
|
||||
(extend-protocol ToSql
|
||||
clojure.lang.Keyword
|
||||
(-to-sql [x] (-> x name (string/replace "-" "_")))
|
||||
(-to-sql [x] (let [s ^String (name x)]
|
||||
(if (= \% (.charAt s 0))
|
||||
(let [call-args (string/split (subs s 1) #"\." 2)]
|
||||
(to-sql (apply call (map keyword call-args))))
|
||||
(-> s (string/replace "-" "_")))))
|
||||
clojure.lang.Symbol
|
||||
(-to-sql [x] (-> x name (string/replace "-" "_")))
|
||||
java.lang.Number
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
(deftest test-select
|
||||
(let [m1 (-> (select :f.* :b.baz :c.quux [:b.bla "bla-bla"]
|
||||
(sql/call :now) (sql/raw "@x := 10"))
|
||||
:%now (sql/raw "@x := 10"))
|
||||
;;(un-select :c.quux)
|
||||
(modifiers :distinct)
|
||||
(from [:foo :f] [:baz :b])
|
||||
|
|
@ -27,7 +27,7 @@
|
|||
(limit 50)
|
||||
(offset 10))
|
||||
m2 {:select [:f.* :b.baz :c.quux [:b.bla "bla-bla"]
|
||||
(sql/call :now) (sql/raw "@x := 10")]
|
||||
:%now (sql/raw "@x := 10")]
|
||||
;;:un-select :c.quux
|
||||
:modifiers :distinct
|
||||
:from [[:foo :f] [:baz :b]]
|
||||
|
|
|
|||
Loading…
Reference in a new issue