-
Notifications
You must be signed in to change notification settings - Fork 85
/
jdbc.clj
157 lines (130 loc) · 5.36 KB
/
jdbc.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
(ns ragtime.jdbc
"Functions for loading SQL migrations and applying them to a SQL database."
(:refer-clojure :exclude [load-file])
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.java.jdbc :as sql]
[clojure.string :as str]
[ragtime.protocols :as p]
[resauce.core :as resauce])
(:import [java.io File]
[java.sql Connection]
[java.text SimpleDateFormat]
[java.util Date]))
(defn- migrations-table-ddl [table-name]
(sql/create-table-ddl table-name
[[:id "varchar(255)"]
[:created_at "varchar(32)"]]))
(defn- get-table-metadata* [^Connection conn]
(with-open [tables (-> conn
(.getMetaData)
(.getTables (.getCatalog conn) nil "%" nil))]
(sql/metadata-result tables)))
(defn- get-table-metadata [db-spec]
(if-let [conn (sql/db-find-connection db-spec)]
(get-table-metadata* conn)
(with-open [conn (sql/get-connection db-spec)]
(get-table-metadata* conn))))
(defn- metadata-matches-table? [^String table-name metadata]
(.equalsIgnoreCase table-name
(if (.contains table-name ".")
(str (:table_schem metadata) "." (:table_name metadata))
(:table_name metadata))))
(defn- table-exists? [db-spec ^String table-name]
(some (partial metadata-matches-table? table-name)
(get-table-metadata db-spec)))
(defn- ensure-migrations-table-exists [db-spec migrations-table]
(when-not (table-exists? db-spec migrations-table)
(sql/execute! db-spec [(migrations-table-ddl migrations-table)])))
(defn- format-datetime [^Date dt]
(-> (SimpleDateFormat. "yyyy-MM-dd'T'HH:mm:ss.SSS")
(.format dt)))
(defrecord SqlDatabase [db-spec migrations-table]
p/DataStore
(add-migration-id [_ id]
(ensure-migrations-table-exists db-spec migrations-table)
(sql/insert! db-spec migrations-table
{:id (str id)
:created_at (format-datetime (Date.))}))
(remove-migration-id [_ id]
(ensure-migrations-table-exists db-spec migrations-table)
(sql/delete! db-spec migrations-table ["id = ?" id]))
(applied-migration-ids [_]
(ensure-migrations-table-exists db-spec migrations-table)
(sql/query db-spec
[(str "SELECT id FROM " migrations-table " ORDER BY created_at")]
{:row-fn :id})))
(defn sql-database
"Given a db-spec and a map of options, return a Migratable database.
The following options are allowed:
:migrations-table - the name of the table to store the applied migrations
(defaults to ragtime_migrations)"
([db-spec]
(sql-database db-spec {}))
([db-spec options]
(->SqlDatabase db-spec (:migrations-table options "ragtime_migrations"))))
(defn- execute-sql! [db-spec statements transaction?]
(doseq [s statements]
(sql/execute! db-spec [s] {:transaction? transaction?})))
(defrecord SqlMigration [id up down transactions]
p/Migration
(id [_] id)
(run-up! [_ db]
(execute-sql! (:db-spec db)
up
(contains? #{:up :both true} transactions)))
(run-down! [_ db]
(execute-sql! (:db-spec db)
down
(contains? #{:down :both true} transactions))))
(defn sql-migration
"Create a Ragtime migration from a map with a unique :id, and :up and :down
keys that map to ordered collection of SQL strings."
[migration-map]
(map->SqlMigration migration-map))
(defn- file-extension [file]
(re-find #"\.[^.]*$" (str file)))
(let [pattern (re-pattern (str "([^\\/]*)\\/?$"))]
(defn- basename [file]
(second (re-find pattern (str file)))))
(defn- remove-extension [file]
(second (re-matches #"(.*)\.[^.]*" (str file))))
(defmulti load-files
"Given an collection of files with the same extension, return a ordered
collection of migrations. Dispatches on extension (e.g. \".edn\"). Extend
this multimethod to support new formats for specifying SQL migrations."
(fn [files] (file-extension (first files))))
(defmethod load-files :default [files])
(defmethod load-files ".edn" [files]
(for [file files]
(-> (slurp file)
(edn/read-string)
(update-in [:id] #(or % (-> file basename remove-extension)))
(update-in [:transactions] (fnil identity :both))
(sql-migration))))
(defn- sql-file-parts [file]
(rest (re-matches #"(.*?)\.(up|down)(?:\.(\d+))?\.sql" (str file))))
(defn- read-sql [file]
(str/split (slurp file) #"(?m)\n\s*--;;\s*\n"))
(defmethod load-files ".sql" [files]
(for [[id files] (->> files
(group-by (comp first sql-file-parts))
(sort-by key))]
(let [{:strs [up down]} (group-by (comp second sql-file-parts) files)]
(sql-migration
{:id (basename id)
:up (vec (mapcat read-sql (sort-by str up)))
:down (vec (mapcat read-sql (sort-by str down)))}))))
(defn- load-all-files [files]
(->> (group-by file-extension files)
(vals)
(mapcat load-files)
(sort-by :id)))
(defn load-directory
"Load a collection of Ragtime migrations from a directory."
[path]
(load-all-files (map #(.toURI ^File %) (file-seq (io/file path)))))
(defn load-resources
"Load a collection of Ragtime migrations from a classpath prefix."
[path]
(load-all-files (resauce/resource-dir path)))