Last active
December 11, 2015 08:49
-
-
Save maio/4575985 to your computer and use it in GitHub Desktop.
Clojure model migrations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Alternatives - http://www.clojure-toolbox.com (Database Migrations) | |
(ns wools.models.migration | |
(:require [clojure.java.jdbc :as sql])) | |
(def migrations | |
[{:id "create balance table" | |
:up #(sql/create-table :balance | |
[:ts :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"] | |
[:amount :int "NOT NULL"])}]) | |
(defmacro show-progress [message & body] | |
`(do | |
(print ~message) (flush) | |
~@body | |
(println " done"))) | |
(defn get-applied-migrations [] | |
(sql/with-query-results results | |
["select id from migrations"] | |
(set (map :id results)))) | |
(defn mark-as-applied [migration] | |
(sql/insert-record :migrations (select-keys migration [:id]))) | |
(defn run-migration [migration] | |
((:up migration)) | |
(mark-as-applied migration)) | |
(defn migrate [migrations applied-migrations] | |
(show-progress | |
"Performing migrations ..." | |
(doseq [migration (filter #(not (applied-migrations (:id %))) migrations)] | |
(run-migration migration)))) | |
(defn initialize [] | |
(show-progress | |
"Going to create migrations table ..." | |
(sql/create-table :migrations | |
[:id :varchar "PRIMARY KEY"] | |
[:applied_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]))) | |
(defn -main | |
([] (println "Usage: migration [initialize|migrate|dwim]")) | |
([command] | |
(sql/with-connection (System/getenv "DATABASE_URL") | |
(cond | |
(= command "initialize") (initialize) | |
(= command "migrate") (migrate migrations (get-applied-migrations)) | |
(= command "dwim") (do | |
(initialize) | |
(migrate migrations (get-applied-migrations))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment