Skip to content

Database: Migrations ​

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:

shell
dotblaze make:migration create_posts_table
dotblaze make:migration add_votes_to_posts_table

A 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:

csharp
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:

csharp
[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:

csharp
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:

shell
dotblaze migrate

Every 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:

shell
dotblaze migrate:rollback

migrate:reset rolls back every migration:

shell
dotblaze migrate:reset

If 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:

shell
dotblaze migrate:fresh
dotblaze migrate:fresh --seed

WARNING

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:

shell
dotblaze migrate:status
text
  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_table

Tables ​

Creating Tables ​

Schema.Create takes the table name and a closure that receives a Blueprint:

csharp
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:

csharp
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 ​

csharp
Schema.Rename("posts", "articles");

Schema.Drop("users");
Schema.DropIfExists("users");

Columns ​

Available Column Types ​

MethodColumnModel 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 keyint Id
t.String("name", length = 255)Variable-length stringstring
t.Text("body")Unlimited textstring
t.Json("data")Text column for JSON (use a JsonCast on the model)your type
t.Integer("votes")intint
t.BigInteger("views")bigintlong
t.SmallInteger("rank")smallintshort
t.Boolean("is_active")Booleanbool
t.Decimal("price", precision = 8, scale = 2)Decimaldecimal
t.Double("ratio")Doubledouble
t.Date("born_on")DateDateOnly
t.DateTime("published_at")Date and timeDateTime
t.Timestamp("seen_at")Same as DateTimeDateTime
t.Uuid("uuid")GUIDGuid
t.Binary("data")Binarybyte[]
t.Vector("embedding", dimensions)pgvector vector(dimensions) on PostgreSQL; JSON text elsewhere. .Index() adds an HNSW cosine index on PostgreSQL. See Vector Searchfloat[]
t.ForeignId("user_id")bigint for a foreign keylong UserId
t.Timestamps()Nullable created_at and updated_atDateTime? CreatedAt, UpdatedAt
t.SoftDeletes()Nullable deleted_atDateTime? DeletedAt
t.RememberToken()Nullable remember_token, length 100string?

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:

csharp
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();
ModifierDescription
.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 ​

csharp
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:

csharp
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:

csharp
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:

csharp
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.

shell
# Run from the Blog application after adding those files.
dotnet build
dotblaze migrate
dotblaze migrate:status
dotblaze db:check

Expected: 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.