Clear ORM
Search…
Call migration script

Call migration script

Clear offers a migration system. Migration allow you to handle state update of your database.
Migration is a list of change going through a direction, up (commit changes) or down (rollback changes).
In clear, a migration is defined like this:
1
class MyMigration1
2
include Clear::Migration
3
4
def change(direction)
5
direction.up do
6
#do something on commit
7
end
8
9
direction.down do
10
#do something on rollback
11
end
12
end
13
end
Copied!

Executing custom SQL

The basic usage is to execute your own SQL (e.g. CREATE TABLE, ALTER, GRANT etc...).
To do it, just call execute into your direction block.

Example

1
class MyMigration1
2
include Clear::Migration
3
4
def change(direction)
5
direction.up do
6
execute("CREATE TABLE my_models...")
7
end
8
9
direction.down do
10
execute("DROP TABLE my_models")
11
end
12
end
13
end
Copied!

Built-in helpers

Clear offers helpers for simplify declaring your migration

Creating a table

Clear provides DSL looking like ActiveRecord for creating a table.
1
create_table(:users) do |t|
2
t.column :first_name, :string, index: true
3
t.column :last_name, :string, unique: true
4
5
# Will create a "user_info_id" field of type longint with a foreign key constraint
6
# This reference can be null, and if the user_info is deleted then the user is deleted too.
7
t.references to: "user_infos", name: "user_info_id", on_delete: "cascade", null: true
8
9
# Example of creating index on full name
10
t.index "lower(first_name || ' ' || last_name)", using: :btree
11
12
t.timestamps
13
end
Copied!

Migration ordering

Migration should be ordered by a number. This number can be written in different way:
  • In case of mixing multiple classes into the same file, you can append the number at the end of the class name:
1
class Migration1
2
include Clear::Migration
3
4
def change(dir)
5
#...
6
end
7
end
Copied!
If you're using one file per migration, you can prepend the ordering number at the start of the file name:
1
1234_migration.cr
Copied!
Finally, if you feel more rock'n'roll and build a complex dynamic migration system on top of Clear, you can override the uid method:
1
class Migration1
2
include Clear::Migration
3
4
def uid
5
123_i64 #Number must be a signed 64bits integer !
6
end
7
8
def change(dir)
9
#...
10
end
11
end
Copied!

Calling your migration

Clear will offers soon a CLI; meanwhile, you can call migration update using methods in the Migration Manager:
1
# Activate all the migrations. Will call change with up direction for each down migrations
2
Clear::Migration::Manager.instance.apply_all
Copied!
1
# Go to a specific migration. All migration with a number above than the version number will be downed if not yet down.
2
# All migrations with a version number below will be activated if not yet up.
3
Clear::Migration::Manager.instance.apply_to(version_number)
Copied!
Last modified 1yr ago