keyword syntax for bindable param

This commit is contained in:
Justin Kramer 2013-08-06 14:27:56 -04:00
parent e768e3c1d1
commit 4590b93df5
3 changed files with 17 additions and 6 deletions

View file

@ -98,6 +98,16 @@ Keywords that begin with `%` are interpreted as SQL function calls:
=> ["SELECT COUNT(*) FROM foo"] => ["SELECT COUNT(*) FROM foo"]
``` ```
Keywords that begin with `?` are interpreted as bindable parameters:
``clj
(-> (select :id)
(from :foo)
(where [:= :a :?baz])
(sql/format {:baz "BAZ"}))
=> ["SELECT id FROM foo WHERE a = ?" "BAZ"]
```
There are helper functions and data literals for SQL function calls, field qualifiers, raw SQL fragments, and named input parameters: There are helper functions and data literals for SQL function calls, field qualifiers, raw SQL fragments, and named input parameters:
```clj ```clj

View file

@ -1,6 +1,6 @@
(ns honeysql.format (ns honeysql.format
(:refer-clojure :exclude [format]) (:refer-clojure :exclude [format])
(:require [honeysql.types :refer [call raw param-name]] (:require [honeysql.types :refer [call raw param param-name]]
[clojure.string :as string]) [clojure.string :as string])
(:import [honeysql.types SqlCall SqlRaw SqlParam])) (:import [honeysql.types SqlCall SqlRaw SqlParam]))
@ -155,9 +155,10 @@
(extend-protocol ToSql (extend-protocol ToSql
clojure.lang.Keyword clojure.lang.Keyword
(-to-sql [x] (let [s ^String (name x)] (-to-sql [x] (let [s ^String (name x)]
(if (= \% (.charAt s 0)) (condp = (.charAt s 0)
(let [call-args (string/split (subs s 1) #"\." 2)] \% (let [call-args (string/split (subs s 1) #"\." 2)]
(to-sql (apply call (map keyword call-args)))) (to-sql (apply call (map keyword call-args))))
\? (to-sql (param (keyword (subs s 1))))
(-> s (string/replace "-" "_"))))) (-> s (string/replace "-" "_")))))
clojure.lang.Symbol clojure.lang.Symbol
(-to-sql [x] (-> x name (string/replace "-" "_"))) (-to-sql [x] (-> x name (string/replace "-" "_")))

View file

@ -16,7 +16,7 @@
(left-join [:clod :c] [:= :f.a :c.d]) (left-join [:clod :c] [:= :f.a :c.d])
(right-join :bock [:= :bock.z :c.e]) (right-join :bock [:= :bock.z :c.e])
(where [:or (where [:or
[:and [:= :f.a "bort"] [:not= :b.baz (sql/param :param1)]] [:and [:= :f.a "bort"] [:not= :b.baz :?param1]]
[:< 1 2 3] [:< 1 2 3]
[:in :f.e [1 (sql/param :param2) 3]] [:in :f.e [1 (sql/param :param2) 3]]
[:between :f.e 10 20]]) [:between :f.e 10 20]])
@ -35,7 +35,7 @@
:left-join [[:clod :c] [:= :f.a :c.d]] :left-join [[:clod :c] [:= :f.a :c.d]]
:right-join [:bock [:= :bock.z :c.e]] :right-join [:bock [:= :bock.z :c.e]]
:where [:or :where [:or
[:and [:= :f.a "bort"] [:not= :b.baz (sql/param :param1)]] [:and [:= :f.a "bort"] [:not= :b.baz :?param1]]
[:< 1 2 3] [:< 1 2 3]
[:in :f.e [1 (sql/param :param2) 3]] [:in :f.e [1 (sql/param :param2) 3]]
[:between :f.e 10 20]] [:between :f.e 10 20]]