Handling Migrations
Migrations in CQL provide a structured way to evolve your database schema over time. They allow you to create, modify, and drop tables and columns in a versioned, reversible manner using Crystal code.
What is a Migration?
A migration is a Crystal class that defines changes to your database schema. Each migration has a unique version number and two methods:
up
: Applies the migration (e.g., creates or alters tables).down
: Reverts the migration (e.g., drops or reverts changes).
Creating a Migration
Create a new migration by subclassing CQL::Migration
and setting a unique version:
self.version
must be unique and increasing (often a timestamp or integer).The
up
method defines the schema changes to apply.The
down
method defines how to revert those changes.
Running Migrations
You can run migrations using your preferred migration runner or a custom script. A typical workflow:
Place migration files in a
db/migrations/
directory.Load and apply migrations in order:
Consult your project's migration runner or CQL's documentation for details on migration management.
Modifying Tables
You can alter existing tables in a migration:
Best Practices
Use a unique, increasing version for each migration.
Write reversible migrations (always provide a
down
method).Keep migrations in version control.
Test migrations on a development database before running in production.
Use descriptive class names (e.g.,
AddAgeToUsers
).
Example: Multiple Migrations
For more on defining models and querying, see the other guides in this directory.
Last updated
Was this helpful?