clojure.java.jdbc jsonb support for postgresql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns xxx.jsonb-test | |
(:require | |
[clojure.test :refer [deftest is use-fixtures]] | |
[clojure.java.jdbc :as jdbc] | |
[cheshire.core :as json] | |
[xxx.db :as test-db :refer [*db*]]) | |
(:import | |
[org.postgresql.util PGobject] | |
[java.sql PreparedStatement])) | |
(use-fixtures :each test-db/fixture) | |
(extend-protocol jdbc/IResultSetReadColumn | |
org.postgresql.util.PGobject | |
(result-set-read-column [val _ _] | |
(when (= "jsonb" (.getType val)) (json/parse-string (.getValue val) true)))) | |
(extend-protocol jdbc/ISQLParameter | |
clojure.lang.IPersistentMap | |
(set-parameter [m ^PreparedStatement s ^long i] | |
(.setObject s i (doto (PGobject.) (.setType "jsonb") (.setValue (json/generate-string m)))))) | |
(deftest read-test (is (= {:a 5} (:val (first (jdbc/query *db* "select '{\"a\":5}'::jsonb as val")))))) | |
(deftest write-test | |
(jdbc/execute! *db* "create table t (val jsonb)") | |
(jdbc/insert! *db* :t {:val {:a 6}}) | |
(is (= {:a 6} (:val (first (jdbc/query *db* "select * from t")))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment