Back

read-as-instant (clj)

(source)

function

(read-as-instant)
After calling this function, `next.jdbc.result-set/ReadableColumn` will be extended to (`java.sql.Date` and) `java.sql.Timestamp` so that any timestamp columns will automatically be read as `java.time.Instant`. Note that `java.sql.Date` columns will still be returned as-is because they cannot be converted to an instant (they lack a time component).

Examples

oxalorg/clojurians-log-v2
(ns clojurians-log.db.core
  (:require [integrant.core :as ig]
            [clojurians-log.db.migrations :as migrations]
            [next.jdbc :as jdbc]
            [next.jdbc.date-time :as jdbc.date-time]))

(defmethod ig/init-key ::datasource [_ config]
  ;; TODO: add connection pooling
  (let [ds (jdbc/get-datasource config)]
    (jdbc.date-time/read-as-instant)
    (jdbc/with-options ds jdbc/unqualified-snake-kebab-opts)))
pilosus/dienstplan
(ns dienstplan.db-test
  (:require
   [clojure.spec.gen.alpha :as gen]
   [clojure.test :refer [deftest is testing use-fixtures]]
   [dienstplan.db :as db]
   [dienstplan.fixture :as fix]
   [dienstplan.spec :as spec]
   [next.jdbc :as jdbc]
   [next.jdbc.sql :as sql]
   [next.jdbc.date-time :as date-time]
   [clojure.spec.alpha :as s]))

(deftest test-db-schema-rota
  (testing "DB table rota"
    (doseq [rota-params params-gen-rota]
      (jdbc/with-transaction [conn db/db]
        (date-time/read-as-instant)
        (let [inserted (sql/insert! conn :rota rota-params)]
          (is (s/valid? ::spec/db-rota inserted)))
        (.rollback conn)))))

(deftest test-db-schema-mention
  (testing "DB table mention"
    (doseq [mention-params params-gen-mention]
      (jdbc/with-transaction [conn db/db]
        (date-time/read-as-instant)
        (let [now (new java.sql.Timestamp (System/currentTimeMillis))
              rota (sql/insert!
                    conn :rota
                    {:name "rota" :channel "chan" :description "my rota"
                     :created_on now :updated_on now})
              params
              (update
               mention-params
               :mention/rota_id
               (constantly (:rota/id rota)))
              inserted (sql/insert! conn :mention params)]
          (is (s/valid? ::spec/db-mention inserted)))
        (.rollback conn)))))