Database: Migrations
- Introduction
- Complete Example: Schema and Model Together
- Generating Migrations
- Migration Structure
- Running Migrations
- Tables
- Columns
- Indexes
- Database Differences
Introduction
Migrations are version control for your database schema. Like Laravel, DotBlaze migrations are hand-written classes with an Up and a Down method that use the Schema builder. One migration works on every supported database: DotBlaze turns the Schema calls into EF Core migration operations, and the active database provider generates the SQL.
DotBlaze does not use EF Core Migrations or EnsureCreated. EF Core only maps models to the tables your migrations create; db:check tells you when the two drift apart (see Checking the Schema).
Generating Migrations
Migrations live in database/migrations. Create one with the generator:
dotblaze make:migration create_posts_table
dotblaze make:migration add_votes_to_posts_tableA create_x_table name produces a Schema.Create stub, a name ending in _to_x_table, _from_x_table, or _in_x_table produces a Schema.Table stub, and --create=table / --table=table pick the table explicitly. You can also write the class by hand: any non-abstract class that extends DotBlaze.Migration in the application assembly is discovered automatically.
Every migration needs a [Migration] attribute with a name in Laravel's yyyy_MM_dd_HHmmss_description format. The name decides the order in which migrations run (ordinal string sort) and is what gets recorded in the migrations table:
namespace App.Database.Migrations;
[Migration("2026_11_26_000000_create_posts_table")]
public class CreatePostsTable : Migration
{
// ...
}A migration without the attribute makes every migrate command fail with an error naming the class.
Migration Structure
Up adds tables, columns, or indexes; Down reverses what Up did:
[Migration("2026_11_26_000000_create_posts_table")]
public class CreatePostsTable : Migration
{
public override void Up() => Schema.Create("posts", t =>
{
t.Id();
t.ForeignId("user_id").Constrained().CascadeOnDelete();
t.String("title");
t.Text("body");
t.Timestamps();
});
public override void Down() => Schema.DropIfExists("posts");
}Up and Down are synchronous: they only describe the changes, which DotBlaze then executes. Schema can only be used inside them; calling it anywhere else throws.
Setting the Migration Connection
A migration runs on the default connection. Override Connection to run it on another connection from config/Database.cs:
public override string? Connection => "pgsql";The record of which migrations have run is always kept in the migrations table on the default connection.
Running Migrations
Built-in commands run through the application itself, like php artisan:
dotblaze migrateEvery migration that has not run yet is executed in name order and recorded in the migrations table with a new batch number. The table is created on first use. Add --seed to run the DatabaseSeeder afterwards (see Seeding).
Rolling Back Migrations
migrate:rollback runs Down for every migration in the last batch, newest first:
dotblaze migrate:rollbackmigrate:reset rolls back every migration:
dotblaze migrate:resetIf the migrations table lists a migration whose class no longer exists, the rollback stops with an error.
Drop All Tables and Migrate
migrate:fresh drops every table on the default connection (not only those created by migrations) and then runs all migrations:
dotblaze migrate:fresh
dotblaze migrate:fresh --seedWARNING
migrate:fresh does not call Down and asks no questions. Never point it at a database you care about. Tables on other connections are not dropped.
Migration Status
migrate:status lists every migration with its batch number, or Pending:
dotblaze migrate:status Ran [1] 0001_01_01_000000_create_users_table
Ran [1] 0001_01_01_000001_create_jobs_table
Pending 2026_11_26_000000_create_posts_tableTables
Creating Tables
Schema.Create takes the table name and a closure that receives a Blueprint:
Schema.Create("users", t =>
{
t.Id();
t.String("name");
t.String("email").Unique();
t.String("password");
t.Timestamps();
});Table and column names are used exactly as written. Use the plural snake_case names that models expect (users, created_at), see Model Conventions.
Updating Tables
Schema.Table changes an existing table. Columns and indexes defined in the closure are added:
Schema.Table("users", t =>
{
t.String("phone").Nullable();
t.Index("phone");
});There is no way to change an existing column's type or rename a column yet.
Renaming and Dropping Tables
Schema.Rename("posts", "articles");
Schema.Drop("users");
Schema.DropIfExists("users");Columns
Available Column Types
| Method | Column | Model property |
|---|---|---|
t.Id() | Auto-increment bigint primary key named id (pass a name to change it) | long Id |
t.Increments("id") | Auto-increment int primary key | int Id |
t.String("name", length = 255) | Variable-length string | string |
t.Text("body") | Unlimited text | string |
t.Json("data") | Text column for JSON (use a JsonCast on the model) | your type |
t.Integer("votes") | int | int |
t.BigInteger("views") | bigint | long |
t.SmallInteger("rank") | smallint | short |
t.Boolean("is_active") | Boolean | bool |
t.Decimal("price", precision = 8, scale = 2) | Decimal | decimal |
t.Double("ratio") | Double | double |
t.Date("born_on") | Date | DateOnly |
t.DateTime("published_at") | Date and time | DateTime |
t.Timestamp("seen_at") | Same as DateTime | DateTime |
t.Uuid("uuid") | GUID | Guid |
t.Binary("data") | Binary | byte[] |
t.Vector("embedding", dimensions) | pgvector vector(dimensions) on PostgreSQL; JSON text elsewhere. .Index() adds an HNSW cosine index on PostgreSQL. See Vector Search | float[] |
t.ForeignId("user_id") | bigint for a foreign key | long UserId |
t.Timestamps() | Nullable created_at and updated_at | DateTime? CreatedAt, UpdatedAt |
t.SoftDeletes() | Nullable deleted_at | DateTime? DeletedAt |
t.RememberToken() | Nullable remember_token, length 100 | string? |
The exact SQL type is chosen by the database provider (for example TEXT for strings on SQLite, character varying(255) on PostgreSQL).
When a table has an Id() or Increments() column and no explicit Primary(...), that column becomes the primary key.
Column Modifiers
Modifiers chain onto a column definition:
t.String("nickname").Nullable();
t.Boolean("is_active").Default(true);
t.DateTime("joined_at").DefaultSql("CURRENT_TIMESTAMP");
t.String("email").Unique();
t.String("title").Index();| Modifier | Description |
|---|---|
.Nullable(bool value = true) | Allow NULL. Columns are NOT NULL by default. |
.Default(value) | Default value. |
.DefaultSql("...") | Default as a raw SQL expression. |
.Unique() | Add a unique index on the column. |
.Index() | Add an index on the column. |
.Length(n) | Maximum length. |
.Precision(p, s) | Precision and scale. |
Dropping Columns
Schema.Table("users", t => t.DropColumn("phone", "nickname"));Indexes
Creating Indexes
Besides the .Unique() and .Index() modifiers, a blueprint can create composite indexes and a composite primary key:
Schema.Create("book_tag", t =>
{
t.ForeignId("book_id").Constrained().CascadeOnDelete();
t.ForeignId("tag_id").Constrained().CascadeOnDelete();
t.Primary("book_id", "tag_id");
});
t.Index("author_id", "published_at");
t.Unique("account_id", "email");Indexes are named {table}_{columns}_index or {table}_{columns}_unique, like Laravel. There is no DropIndex yet.
Foreign Key Constraints
ForeignId creates the bigint column; Constrained adds the foreign key. Without arguments, the referenced table is guessed from the column name (user_id → users.id); pass a table and column to override it:
t.ForeignId("user_id").Constrained();
t.ForeignId("author_id").Constrained("users");
t.ForeignId("parent_code").Constrained("categories", "code");Choose what happens when the parent row is deleted:
t.ForeignId("user_id").Constrained().CascadeOnDelete();
t.ForeignId("editor_id").Nullable().Constrained("users").NullOnDelete();Without either, the database refuses to delete a parent that still has children. CascadeOnDelete and NullOnDelete must come after Constrained. Foreign keys are named {table}_{column}_foreign.
Database Differences
The same migration runs everywhere, but each database still has its own limits. In particular, SQLite cannot alter existing tables in many ways: EF Core's SQLite provider refuses some operations on existing tables, such as adding a foreign key constraint with Schema.Table. Put foreign keys in Schema.Create, or create a new table and copy the data.
Schema.DropIfExists runs DROP TABLE IF EXISTS, which every supported database understands.
Schema.EnsureVectorExtensionExists() runs CREATE EXTENSION IF NOT EXISTS vector on PostgreSQL (call it before creating Vector columns) and does nothing on other databases, where vectors are stored as JSON text.
Complete Example: Schema and Model Together
Use the full CreatePostsTable and Post files. They agree on long IDs, required title/body, nullable UTC timestamps, and the author foreign key.
# Run from the Blog application after adding those files.
dotnet build
dotblaze migrate
dotblaze migrate:status
dotblaze db:checkExpected: the post migration is marked as run and db:check reports no missing model columns. Running migrate again does not recreate the table. To practice rollback, use a disposable learning database: migrate:rollback runs Down for the entire last batch, so it may drop more than the posts table if other migrations ran in that batch.
The foreign-key test proves cascading deletion, and the transaction test proves application writes roll back. Keep migration IDs stable after deployment; adding a new model field requires a new migration rather than editing an already-applied Up.