summaryrefslogtreecommitdiff
path: root/src/clojure_sql/core.clj
blob: e77eeb06d86c31844af6d68c3225d29ef828adbd (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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
(ns clojure-sql.core
  (:refer-clojure :exclude [sort])
  (:require [clojure.set :as set]
            [clojure-sql.compiler :as c]
            [clojure-sql.dsl :as d]
            [clojure-sql.query :as q]
            [clojure-sql.util :as u]
            [clojure.walk]))

(def ^:private ^:dynamic *database-type* nil)
(defn set-database-type! [new-type]
  (alter-var-root #'*database-type* (constantly new-type))
  nil)

(def ^:private ^:dynamic *query-executor* (comp second vector))
(defn set-query-executor! [exec-fn]
  (alter-var-root #'*query-executor* (constantly exec-fn))
  nil)



(defmethod print-method clojure_sql.query.Query [query writer]
  (binding [*out* writer]
    (pr (c/compile *database-type* query))))


(def table #'d/table)
(def project #'d/project)
(def rename #'d/rename)
(def join #'d/join)
(def select #'d/select)
(def group #'d/group)
(def having #'d/having)
(def sort #'d/sort)

;(def take #'d/take)
;(def drop #'d/drop)


(defn run-query [query]
  (assert *query-executor* "Cannot execute a query without a query executor")
  (*query-executor* :query (c/compile *database-type* query)))

(defn insert! [query & records]
  (assert *query-executor* "Cannot execute a query without a query executor")
  (let [compiled (apply c/insert! *database-type* query records)]
    (*query-executor* :insert compiled)))

(defn update! [query partial-record]
  (assert *query-executor* "Cannot execute a query without a query executor")
  (let [compiled (c/update! *database-type* query partial-record)]
    (*query-executor* :update compiled)))

(defn delete! [query]
  (assert *query-executor* "Cannot execute a query without a query executor")
  (let [compiled (c/delete! *database-type* query)]
    (*query-executor* :delete compiled)))

(q/set-query-deref-behaviour! run-query)



(try
  (require '[clojure.java.jdbc :as jdbc])
  (defn use-jdbc! [connection-string]
    (set-query-executor! (fn [type query] 
                           (jdbc/with-connection connection-string
                             (case type
                               :query (jdbc/with-query-results results query
                                        (vec results))
                               :insert (jdbc/do-prepared-return-keys (first query) (next query))
                               (jdbc/do-prepared (first query) (next query)))))))

  (catch Exception e
    ))