Skip to content

Instantly share code, notes, and snippets.

@ccann
Last active July 18, 2017 01:31
Show Gist options
  • Save ccann/bd2cdc3230b51748884e418186ec3773 to your computer and use it in GitHub Desktop.
Save ccann/bd2cdc3230b51748884e418186ec3773 to your computer and use it in GitHub Desktop.
quick Hull prototype -- fusing schema, toucan, coercer
(ns hull.common
(:require [clojure.data.json :as json])
(:import org.postgresql.util.PGobject))
(defn encode-jsonb
[m]
(doto (PGobject.)
(.setType (name "jsonb"))
(.setValue (json/write-str m))))
(defn decode-jsonb
[^PGobject obj]
(json/read-str (str obj) :key-fn keyword))
(add-type! :jsonb
:in common/encode-jsonb
:out common/decode-jsonb)
(ns hull.core
(:gen-class)
(:require [clojure.data.json :as json]
[coercer.core :refer [coerce]]
[environ.core :refer [env]]
[hikari-cp.core :as conn-pool]
[hull.common :as common]
[mount.core :refer [defstate]]
[schema.core :as s :refer [defschema]]
[toucan.models :as models]))
(defstate db-conn
:start (conn-pool/make-datasource
{:adapter "postgresql"
:register-mbeans true
:auto-commit true
:read-only false
:database-name (or (env :db-name) "hull")
:server-name (or (env :db-host) "localhost")
:username (or (env :db-user) "hull")
:password (or (env :db-password) "")})
:stop (conn-pool/close-datasource db-conn))
(defstate models
:start (models/set-root-namespace! 'hull.models))
(defschema JSONB
(s/constrained s/Str json/read-str "valid-json?"))
(defn add-types!
[]
(models/add-type! JSONB
:in common/encode-jsonb
:out common/decode-jsonb)
(models/add-type! s/Int
:in #(coerce % Integer)
:out #(coerce % Long))
(models/add-type! s/Str
:in #(coerce % String)
:out identity))
(defstate types
:start (add-types!))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
(ns hull.models.asset-types
(:require [coercer.core :refer [coerce]]
[hull.common :as common]
[toucan.models :as models :refer [add-type! defmodel IModelDefaults]]
[schema.core :as s :refer [defschema]]
[clojure.data.json :as json]))
(defmodel AssetType :asset_types)
(defschema JSONB
(s/constrained s/Str json/read-str "valid-json?"))
(defschema AssetTypeData
{:id s/Int
:name s/Str
:version s/Int
:document_schema JSONB})
;; merge the database model with the schema via :types coercion where :types is the schema itself
;; coerce types on input and output. e.g. :document_schema is jsonb type (see add-type! in common.clj)
(extend (class AssetType)
(merge IModelDefaults
{:types (constantly AssetTypeData)}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment