Migratus is a wonderful migration tool for Clojure. You can use it on its own, or if you have a Luminus project, it is already included.
There are a few areas that could use some extra tutorials, though. One of them is code-based migrations. Especially, examples on how to modify the database would be nice.
Here’s a quick explanation of how to modify the database with a code-based migration in Migratus.
First, create an *.edn file in the folder with the regular migrations. It takes the same format as other migrations, so you can really just change the extension of one of your created migrations to ‘.edn’ and change the contents.
The contents of your ‘edn’ file should be
1 2 3 |
{:ns my-app.migrations.some-file :up-fn migrate-up :down-fn migrate-down} |
The namespace specified with ‘:ns’ needs to exist, so create it. Now, copy the following to the Clojure file.
1 2 3 4 5 6 7 8 9 |
(ns my-app.migrations.some-file) (defn migrate-up [config] ;; any code here ) (defn migrate-down [config] ;; any code here ) |
That’s nice, but how do you change the database?
My recommendation is to import next.jdbc into your project. You have an active JDBC connection in the config argument that is passed into the migrate-up and migrate-down functions. You can use that connection as your next.jdbc data source (ds).
Here’s a quick example of the Clojure end of the code-based migration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
(ns my-app.migrations.some-file (:require [clojure.tools.logging :as log] [next.jdbc :as jdbc] )) (defn migrate-up [config] (log/info "UP migration"); (let [mysql (str "CREATE TABLE people (person_pk int, name varchar(255))")] (jdbc/execute! (-> config :conn :connection) [mysql]) )) (defn migrate-down [config] ;; you get the idea (log/info "DOWN migration"); ) |