Skip to content

Instantly share code, notes, and snippets.



Created Mar 12, 2018
What would you like to do?
sql macro; finding a short path to named parameters
(ns sql)
(defn sub-qmark [i form]
(if (keyword? form)
['? form] ;;todo need a stateful transducer
(defn params [body]
(map-indexed sub-qmark body))
(defn q-vec? [form]
(and (vector? form) (= '? (first form))))
(defn pop-qmark [form]
(if (q-vec? form)
(defn pop-indexes [body]
(->> body
(filter q-vec?)
(map second)))
(defn pop-qmarks [body]
(map pop-qmark body))
(defmacro sql [& body]
(let [param-indexes (params body)
just-sql (clojure.string/join " " (pop-qmarks param-indexes))
vars (pop-indexes param-indexes)]
`(fn [args#]
;; todo validate all vars are in args
(into [~just-sql] (map #(get args# %) '~vars)))))
(-> '(select * from :wat :who :wat)
(def select-stuff (sql select * from :wat :who))
{:wat "a"
:who "b"})
;;=> ["select * from ? ?" "a" "b"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.