-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.clj
102 lines (72 loc) · 2.19 KB
/
db.clj
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
(ns automigrate.util.db
"Utils for working with database."
(:require [next.jdbc :as jdbc]
[next.jdbc.result-set :as jdbc-rs]
[honey.sql :as honey]
[clojure.string :as str]))
(def MIGRATIONS-TABLE
"Default migrations table name."
:automigrate-migrations)
; Additional sql clauses
; TODO: update custom clauses with more precise formatters
(honey/register-clause! :drop-constraint
(fn [k spec]
(#'honey/format-selector k spec))
:rename-table)
(honey/register-clause! :add-constraint
(fn [k spec]
(#'honey/format-add-item k spec))
:drop-constraint)
(honey/register-clause! :create-index
(fn [k spec]
(#'honey/format-add-item k spec))
:add-index)
(honey/register-clause! :create-unique-index
(fn [k spec]
(#'honey/format-add-item k spec))
:add-index)
(honey/register-clause! :create-type
(fn [k spec]
(#'honey/format-add-item k spec))
:create-unique-index)
(honey/register-clause! :drop-type
(fn [k spec]
(#'honey/format-add-item k spec))
:create-type)
(honey/register-clause! :alter-type
(fn [k spec]
(#'honey/format-add-item k spec))
:drop-type)
; Public
(defn db-conn
"Return db connection for performing migration."
[jdbc-url]
(jdbc/get-datasource {:jdbcUrl jdbc-url}))
(defn fmt
"Format data to sql query with configured dialect."
([data]
(fmt data nil))
([data dialect]
(if (some? dialect)
(honey/format data {:dialect dialect})
(honey/format data))))
(defn exec!
"Send query to db."
[db query]
(let [fmt-query (fmt query)]
(jdbc/execute! db fmt-query {:builder-fn jdbc-rs/as-unqualified-lower-maps})))
(defn exec-raw!
"Send raw sql query to db."
[db query]
(jdbc/execute! db [query] {:builder-fn jdbc-rs/as-unqualified-lower-maps}))
(defn create-migrations-table
"Create table to keep migrations history."
[db migrations-table]
(->> {:create-table [migrations-table :if-not-exists]
:with-columns [[:id :serial [:not nil] [:primary-key]]
[:name [:varchar 255] [:not nil] :unique]
[:created_at :timestamp [:default [:now]]]]}
(exec! db)))
(defn kw->raw
[kw]
[:raw (str/replace (name kw) #"-" " ")])