Create a Migration

This guide shows you how to create database migrations to manage schema changes.

Migration File Structure

Create migration files in a migrations/ directory:

migrations/
├── 001_create_users.cr
├── 002_create_posts.cr
└── 003_add_email_index.cr

Basic Migration

# migrations/001_create_users.cr
class CreateUsers < CQL::Migration(1)
  def up
    schema.table :users do
      primary :id, Int64, auto_increment: true
      column :name, String, null: false
      column :email, String, null: false
      timestamps
    end

    schema.users.create!
  end

  def down
    schema.users.drop!
  end
end

Migration Number

The number in CQL::Migration(N) must be unique. Use sequential numbers or timestamps:

Create Table

Add Columns

Add Index

Add Foreign Key

Rename Column

Change Column Type

Irreversible Migration

Some migrations can't be reversed:

Verify Migration

Create a simple test:

Last updated

Was this helpful?