Skip to content

Instantly share code, notes, and snippets.

@piranha
Created February 16, 2015 14:39
Show Gist options
  • Save piranha/2f5be420a687eb26fd45 to your computer and use it in GitHub Desktop.
Save piranha/2f5be420a687eb26fd45 to your computer and use it in GitHub Desktop.
;; extend honeysql
(defmethod honeyhelpers/build-clause :returning [ _ m cols]
(assoc m :returning (honeyhelpers/collify cols)))
(defmethod honeyfmt/format-clause :returning [[_ cols] _]
(str "RETURNING " (honeyfmt/comma-join (map honeyfmt/to-sql cols))))
(extend-protocol honeyfmt/ToSql
clojure.lang.Sequential
(-to-sql [x]
(cond
;; list argument in fn call
honeyfmt/*fn-context?*
(honeyfmt/paren-wrap (honeyfmt/comma-join (map honeyfmt/to-sql x)))
;; array in :values or in :set
(contains? #{:values :set} honeyfmt/*clause*)
(do (swap! honeyfmt/*param-names* conj
(keyword (str "_" (swap! honeyfmt/*param-counter* inc))))
(swap! honeyfmt/*params* conj x)
"?")
;; alias
:else
(str (honeyfmt/to-sql (first x))
;; Omit AS in FROM, JOIN, etc. - Oracle doesn't allow it
(if (= :select honeyfmt/*clause*)
" AS "
" ")
(if (string? (second x))
(honeyfmt/quote-identifier (second x))
(honeyfmt/to-sql (second x)))))))
(defn is-not-null [field]
(sql/raw (str (honeyfmt/to-sql field) " IS NOT NULL")))
(defn or-zero [field]
(sql/raw (str "COALESCE(" (honeyfmt/to-sql field) ", 0)")))
;; extend JDBC
(extend-protocol jdbc/ISQLValue
org.joda.time.DateTime
(sql-value [v]
(c/to-sql-time v))
clojure.lang.PersistentVector
(sql-value [v]
(let [c (jdbc/get-connection *db-spec*)]
(.createArrayOf c "text" (into-array v)))))
(extend-protocol jdbc/IResultSetReadColumn
java.sql.Timestamp
(result-set-read-column [v _ _]
(c/from-sql-time v))
org.postgresql.jdbc4.Jdbc4Array
(result-set-read-column [v _ _]
(into [] (.getArray v))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment