babashka / babashka-sql-pods

Babashka pods for SQL databases
Eclipse Public License 1.0
85 stars 17 forks source link

Convert array handling to transit as well #39

Closed borkdude closed 3 years ago

borkdude commented 3 years ago

We can do this after we have given the transit handlers a proper test

clojure -Sdeps '{:deps {com.cognitect/transit-clj {:mvn/version "RELEASE"}}}' -M /tmp/transit.clj
(require '[cognitect.transit :as transit])

(def ldt-read-handler (transit/read-handler #(java.time.LocalDateTime/parse %)))

(defn read-transit [^String v]
  (transit/read
   (transit/reader
    (java.io.ByteArrayInputStream. (.getBytes v "utf-8"))
    :json
    {:handlers {"pod.babashka.sql/local-date-time" ldt-read-handler}})))

(def ldt-write-handler (transit/write-handler "pod.babashka.sql/local-date-time" str))

(def string-array (Class/forName "[Ljava.lang.String;"))

(def string-array-write-handler (transit/write-handler "pod.babashka.sql/string-array" vec))

(defn write-transit [v]
  (let [baos (java.io.ByteArrayOutputStream.)]
    (transit/write (transit/writer baos :json {:handlers {string-array string-array-write-handler
                                                          java.time.LocalDateTime ldt-write-handler}}) v)
    (.toString baos "utf-8")))

(prn (write-transit (into-array String ["foo"])))
borkdude commented 3 years ago

Depends on https://github.com/cognitect/transit-clj/issues/51

borkdude commented 3 years ago

Another interesting tidbit. We can make client-side wrappers that produce a tagged-value so we receive it in the pod and can do what we want with it.

;; clojure -Sdeps '{:deps {com.cognitect/transit-clj {:mvn/version "RELEASE"}}}' -M /tmp/array.clj

(require '[cognitect.transit :as transit])

(defn write-transit [v]
  (let [baos (java.io.ByteArrayOutputStream.)]
    (transit/write (transit/writer baos :json) v)
    (.toString baos "utf-8")))

(defn read-transit [s]
  (let [bais (java.io.ByteArrayInputStream. (.getBytes s "UTF-8"))]
    (transit/read (transit/reader bais :json
                                  {:handlers {"dude" (transit/read-handler (fn [rep]
                                                                             {:dude rep}))}}))))

(def tagged-val (transit/tagged-value "dude" [1 2 3]))

(prn (read-transit (write-transit tagged-val)))