Skip to content

Instantly share code, notes, and snippets.

@alandipert
Last active August 29, 2015 14:09
Show Gist options
  • Save alandipert/64a598b9e26eb0a0ac96 to your computer and use it in GitHub Desktop.
Save alandipert/64a598b9e26eb0a0ac96 to your computer and use it in GitHub Desktop.
deterpolate
(defn deterpolate [s]
(loop [tokens (interpolate s)
out-str (StringBuffer.)
out-args []]
(if (seq tokens)
(let [token (first tokens)]
(cond (string? token)
(recur (rest tokens)
(doto out-str (.append token))
out-args)
(vector? token)
(recur (rest tokens)
(doto out-str (.append (str/join "," (map (constantly "?") token))))
(into out-args token))
:else
(recur (rest tokens)
(doto out-str (.append "?"))
(conj out-args token))))
(into [(str out-str)] out-args))))
@alandipert
Copy link
Author

user=> (deterpolate "select * from foo where x < ~{x} and y in (~{[a,b,3]})")
["select * from foo where x < ? and y in (?,?,?)" x a b 3]

@martinklepsch
Copy link

@alandipert a useful addition might be to support use cases like:

(let [ids [1 2 3 4 5]]
  (deterpolate "SELECT * FROM foo WHERE id IN (~{ids})"))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment