Added Inlinable protocol for more sensible stringification of inline values, and to allow library users to further extend the inline behavior (#224)

This commit is contained in:
Vincent 2018-08-30 18:55:53 +02:00
parent 2b238c5a47
commit 6e3631822d
3 changed files with 24 additions and 5 deletions

View file

@ -1,6 +1,7 @@
(ns honeysql.format
(:refer-clojure :exclude [format])
(:require [honeysql.types :refer [call raw param param-name
(:require [honeysql.types :as types
:refer [call raw param param-name inline-str
#?@(:cljs [SqlCall SqlRaw SqlParam SqlArray SqlInline])]]
[clojure.string :as string])
#?(:clj (:import [honeysql.types SqlCall SqlRaw SqlParam SqlArray SqlInline])))
@ -357,6 +358,18 @@
(quote-identifier (second x))
(to-sql (second x))))))
(extend-protocol types/Inlinable
#?(:clj clojure.lang.Keyword
:cljs cljs.core/Keyword)
(inline-str [x]
(name x))
nil
(inline-str [_]
"NULL")
#?(:clj Object :cljs default)
(inline-str [x]
(str x)))
(extend-protocol ToSql
#?(:clj clojure.lang.Keyword
:cljs cljs.core/Keyword)
@ -411,10 +424,7 @@
(str "ARRAY[" (comma-join (map to-sql (.-values x))) "]"))
SqlInline
(to-sql [x]
(let [v (.-value x)]
(if (some? v)
(str v)
"NULL")))
(inline-str (.-value x)))
#?(:clj Object :cljs default)
(to-sql [x]
#?(:clj (add-anon-param x)

View file

@ -61,6 +61,9 @@
(defrecord SqlInline [value])
(defprotocol Inlinable
(inline-str [x]))
(defn inline
"Prevents parameterization"
[value]

View file

@ -214,3 +214,9 @@
:join [[:table2 :t2] [:= :t1.fk :t2.id]]
:where [:= :t1.bar 42]}
(format :quoting :mysql)))))
(deftest inlined-values-are-stringified-correctly
(is (= ["SELECT foo, bar, NULL"]
(format {:select [(honeysql.core/inline "foo")
(honeysql.core/inline :bar)
(honeysql.core/inline nil)]}))))