Migrations

Database Migrations with micrate

If you're using Granite to query your data, you likely want to manage your database schema as well. Migrations are a great way to do that, so let's take a look at micrate, a project to manage migrations. We'll use it as a dependency instead of a pre-build binary.

Install

Add micrate your shards.yml
1
dependencies:
2
micrate:
3
github: juanedi/micrate
Copied!
Update shards
1
$ shards update
Copied!
Create an executable to run the Micrate::Cli. For this example, we'll create bin/micrate in the root of our project where we're using Granite ORM. This assumes you're exporting the DATABASE_URL for your project and an environment variable instead of using a database.yml.
1
#! /usr/bin/env crystal
2
#
3
# To build a standalone command line client, require the
4
# driver you wish to use and use `Micrate::Cli`.
5
#
6
7
require "micrate"
8
require "pg"
9
10
Micrate::DB.connection_url = ENV["DATABASE_URL"]
11
Micrate::Cli.run
Copied!
Make it executable:
1
$ chmod +x bin/micrate
Copied!
We should now be able to run micrate commands.
$ bin/micrate help => should output help commands.

Creating a migration

Let's create a posts table in our database.
1
$ bin/micrate scaffold create_posts
Copied!
This will create a file under db/migrations. Let's open it and define our posts schema.
1
-- +micrate Up
2
-- SQL in section 'Up' is executed when this migration is applied
3
CREATE TABLE posts(
4
id BIGSERIAL PRIMARY KEY,
5
title VARCHAR NOT NULL,
6
body TEXT NOT NULL,
7
created_at TIMESTAMP,
8
updated_at TIMESTAMP
9
);
10
11
-- +micrate Down
12
-- SQL section 'Down' is executed when this migration is rolled back
13
DROP TABLE posts;
Copied!
And now let's run the migration
1
$ bin/micrate up
Copied!
You should now have a posts table in your database ready to query.
Last modified 1mo ago