Skip to content

Instantly share code, notes, and snippets.

@teaforthecat

teaforthecat/sql.clj

Created Mar 12, 2018
Embed
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
form))
(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)
'?
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)))))
(comment
(-> '(select * from :wat :who :wat)
(params)
(pop-indexes)
)
(def select-stuff (sql select * from :wat :who))
(select-stuff
{: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.