Skip to content

Instantly share code, notes, and snippets.

@danieroux
Created October 1, 2021 22:14
Show Gist options
  • Save danieroux/c44397ea378ee34b9534b36aba557924 to your computer and use it in GitHub Desktop.
Save danieroux/c44397ea378ee34b9534b36aba557924 to your computer and use it in GitHub Desktop.
Turning a Clojure keyword into a SQL-safe name
(def ^:private make-boring-regex #"[*.?!:+-]")
(defn sql-name
"Makes `kw` a SQL-safe string.
/ becomes __
All other SQL-unsafe chars become _"
[kw]
(let [name-xf (clojure.string/replace (name kw) make-boring-regex "_")]
(if (namespace kw)
(let [ns-xf (clojure.string/replace (namespace kw) make-boring-regex "_")]
(str ns-xf "__" name-xf))
name-xf)))
(s/fdef sql-name
:args (s/cat :keyword keyword?)
:ret #(re-matches #"([A-Za-z0-9_]+__)?[A-Za-z0-9_]+" %))
(comment
(sql-name :keyword/beyond-2000)
(check! #{"keyword__beyond_2000"})
(sql-name :json-data)
(check! #{"json_data"})
())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment