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.
Add micrate your shards.yml
$ shards update
Create an executable to run the
Micrate::Cli. For this example, we'll create
bin/micratein the root of our project where we're using Granite ORM. This assumes you're exporting the
DATABASE_URLfor your project and an environment variable instead of using a
#! /usr/bin/env crystal
# To build a standalone command line client, require the
# driver you wish to use and use `Micrate::Cli`.
Micrate::DB.connection_url = ENV["DATABASE_URL"]
Make it executable:
$ chmod +x bin/micrate
We should now be able to run micrate commands.
$ bin/micrate help=> should output help commands.
Let's create a
poststable in our database.
$ bin/micrate scaffold create_posts
This will create a file under
db/migrations. Let's open it and define our posts schema.
-- +micrate Up
-- SQL in section 'Up' is executed when this migration is applied
CREATE TABLE posts(
id BIGSERIAL PRIMARY KEY,
title VARCHAR NOT NULL,
body TEXT NOT NULL,
-- +micrate Down
-- SQL section 'Down' is executed when this migration is rolled back
DROP TABLE posts;
And now let's run the migration
$ bin/micrate up
You should now have a
poststable in your database ready to query.