Skip to content

Instantly share code, notes, and snippets.

@thomascothran
Last active November 17, 2023 01:24
Show Gist options
  • Save thomascothran/dd378fd99dc239abf4cc0c8037e43d91 to your computer and use it in GitHub Desktop.
Save thomascothran/dd378fd99dc239abf4cc0c8037e43d91 to your computer and use it in GitHub Desktop.
Inquest
(ns tech.thomascothran.inquest
"A quest for the perf and security benefits of parameterized queries
with the feel of inquery
Usage with deps:
```
{:deps {tech.thomascothran.inquest {:git/url <this-url>
:git/sha <this-sha>}}}
```")
(defn parameterized-query [query params]
(let [sorted-keys (->> (keys params) set (sort-by (comp - count str)))
first-match (fn [s]
(some-> (re-pattern (clojure.string/join "|" sorted-keys))
(re-find s)
(subs 1)
keyword))]
(loop [query-str query
param-map []]
(if-let [match (first-match query-str)]
(recur (clojure.string/replace-first query-str (str match) "?")
(conj param-map (match params)))
(into [query-str] param-map)))))
(comment
;; It's important to handle keys that may collide, where one key is shorter than another
(let [query-string "SELECT * from users WHERE first_name = :first-name AND email = :email and first-name-suffix = :first-name-suffix AND name = :first-name"
parameter-map {:first-name "Thomas"
:email "[email protected]"
:first-name-suffix "Jr"
:first "DO I colled?"}]
(= ["SELECT * from users WHERE first_name = ? AND email = ? and first-name-suffix = ? AND name = ?"
"Thomas"
"[email protected]"
"Jr"
"Thomas"]
(parameterized-query query-string parameter-map))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment