Created
November 6, 2013 09:33
-
-
Save squidsoup/7333383 to your computer and use it in GitHub Desktop.
Migrations Technomancy style (from https://github.com/technomancy/syme/blob/master/src/syme/db.clj)
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
(ns syme.db | |
(:require [clojure.java.jdbc :as sql] | |
[environ.core :as env] | |
[tentacles.repos :as repos]) | |
(:import (java.util UUID)) | |
(:refer-clojure :exclude [find])) | |
(def db (env/env :database-url "postgres://localhost:5432/syme")) | |
;; snip | |
;; migrations | |
(defn initial-schema [] | |
(sql/create-table "instances" | |
[:id :serial "PRIMARY KEY"] | |
[:owner :varchar "NOT NULL"] | |
[:project :varchar "NOT NULL"] | |
[:ip :varchar] | |
[:description :text] | |
[:status :varchar] | |
[:at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]) | |
(sql/create-table "invites" | |
[:id :serial "PRIMARY KEY"] | |
[:invitee :varchar "NOT NULL"] | |
[:instance_id :integer "NOT NULL"] | |
[:at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"])) | |
(defn add-instance-id [] | |
(sql/do-commands "ALTER TABLE instances ADD COLUMN instance_id VARCHAR")) | |
(defn add-shutdown-token [] | |
(sql/do-commands "ALTER TABLE instances ADD COLUMN shutdown_token VARCHAR")) | |
(defn add-dns [] | |
(sql/do-commands "ALTER TABLE instances ADD COLUMN dns VARCHAR")) | |
(defn add-region [] | |
(sql/do-commands "ALTER TABLE instances ADD COLUMN region VARCHAR")) | |
;; migrations mechanics | |
(defn run-and-record [migration] | |
(println "Running migration:" (:name (meta migration))) | |
(migration) | |
(sql/insert-values "migrations" [:name :created_at] | |
[(str (:name (meta migration))) | |
(java.sql.Timestamp. (System/currentTimeMillis))])) | |
(defn migrate [& migrations] | |
(sql/with-connection db | |
(try (sql/create-table "migrations" | |
[:name :varchar "NOT NULL"] | |
[:created_at :timestamp | |
"NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]) | |
(catch Exception _)) | |
(sql/transaction | |
(let [has-run? (sql/with-query-results run ["SELECT name FROM migrations"] | |
(set (map :name run)))] | |
(doseq [m migrations | |
:when (not (has-run? (str (:name (meta m)))))] | |
(run-and-record m)))))) | |
(defn -main [] | |
(migrate #'initial-schema | |
#'add-instance-id | |
#'add-shutdown-token | |
#'add-dns | |
#'add-region)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment