diff --git a/README.md b/README.md index 118013b..7602663 100644 --- a/README.md +++ b/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. diff --git a/src/honeysql/format.clj b/src/honeysql/format.clj index 41afd58..1420826 100644 --- a/src/honeysql/format.clj +++ b/src/honeysql/format.clj @@ -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 diff --git a/test/honeysql/core_test.clj b/test/honeysql/core_test.clj index 5e8c383..f77d271 100644 --- a/test/honeysql/core_test.clj +++ b/test/honeysql/core_test.clj @@ -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]]