Run Migrations

This guide shows you how to create and run database migrations with CQL.

Creating a Migration

Create a migration file:

# db/migrations/001_create_users.cr
class CreateUsers < CQL::Migration
  def up
    create_table :users do
      primary :id, Int64
      column :name, String
      column :email, String
      timestamps
    end

    create_index :users, :email, unique: true
  end

  def down
    drop_table :users
  end
end

Migration Operations

Create Table

Add Column

Remove Column

Rename Column

Change Column

Create Index

Add Foreign Key

Rename Table

Drop Table

Running Migrations

Run All Pending

Run from Command Line

Example CLI:

Rollback Last Migration

Rollback Multiple

Reset Database

Migration Best Practices

Numbered Migrations

Name migrations with timestamps or sequence numbers:

Reversible Migrations

Always implement both up and down:

Data Migrations

Handle data in migrations carefully:

Batch Updates

For large tables, update in batches:

See Also

Last updated

Was this helpful?