summaryrefslogtreecommitdiff
path: root/src/clojure_sql/jdbc.clj
blob: 44ed55ebe748bb60619a6e8c82aa380e42047216 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
(ns clojure-sql.jdbc
  (:require [clojure.java.jdbc :as jdbc]
            [clojure-sql.core :refer [set-query-executor!]]
            [clojure.string :as string]))

(defn ^:private dotted-to-nested-map-one [obj]
  (reduce (fn [acc [key val]]
            (let [dotted (name key)
                  keys (string/split dotted #"\.")
                  keywords (map keyword keys)]
              (assert (nil? (get-in acc keywords nil))
                      "Error converting fields to maps: conflicting paths.")
              (assoc-in acc keywords val)))
          {} obj))

(defn ^:private dotted-to-nested-maps [objs]
  (mapv dotted-to-nested-map-one objs))

(defn use-jdbc! [connection-string]
  (set-query-executor! (fn [type query] 
                         (jdbc/with-connection connection-string
                           (case type
                             :select (jdbc/with-query-results results query
                                       (dotted-to-nested-maps results))
                             :insert (jdbc/do-prepared-return-keys (first query) (next query))
                             :update (jdbc/do-prepared-return-keys (first query) (next query))
                             :delete (first (jdbc/do-prepared (first query) (next query)))
                             (assert false (str "Unknown query type: " type)))))))