dust

Database: Schema Builder

Introduction

Every database engine uses slightly different DDL syntax for CREATE TABLE and ALTER TABLE, so raw schema SQL written for PostgreSQL may fail against the SQLite database used in local tests. dust-framework's schema builder lets you define tables, columns, and indexes once in Rust while generating database-specific SQL for PostgreSQL, MySQL, MariaDB, and SQLite.

Most schema changes live inside migrations. You may call schema() on the migration's transaction to create or alter tables:

rust
// database/migrations/2026_10_27_143000_create_posts_table.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    tx.schema()        .create("posts", |table| {            table.id();            table.foreign_id("user_id").constrained().cascade_on_delete();            table.string("title");            table.string("slug").unique();            table.text("body").nullable();            table.timestamp("published_at").nullable();            table.timestamps();            table.index(["user_id", "published_at"]);        })        .await}

Each schema operation runs when you .await it, so call tx.schema() again for each additional statement inside your migration's migrate function:

rust
tx.schema().drop_if_exists("drafts").await?;tx.schema().rename("articles", "posts").await?;

To inspect the SQL a schema operation will execute without running it, call to_sql() instead of awaiting it.

How schema changes run

schema() returns a handle bound to one connection or one migration transaction. Each builder method consumes that handle and returns a change; awaiting the change is what executes it. That is why a migration calls tx.schema() again for its next statement instead of reusing the first handle.

The SQL is generated when the change is awaited, from the connection's driver. The same table.enumeration(..) becomes a native enum on MySQL and MariaDB, and a varchar with a check constraint on PostgreSQL and SQLite. When a driver cannot express a column or index at all, the operation fails with an error naming the driver instead of emitting invalid SQL; optional keywords the driver lacks are simply omitted.

On MySQL and MariaDB, a DDL statement commits the surrounding transaction. A migration changes one table per file on those drivers so a later failure cannot leave half of a larger change applied. PostgreSQL and SQLite run DDL inside the transaction, so a failed migration rolls back as a unit.

Tables

Creating tables

To create a new database table, pass the table name and a closure to create. The closure receives a Blueprint instance that you may use to define the table's columns, indexes, and constraints:

rust
tx.schema()    .create("flights", |table| {        table.id();        table.string("name");        table.string("airline");        table.timestamps();    })    .await?;

Changing tables

To modify an existing table, call alter with the table name and a Blueprint closure. Defining columns inside alter adds them to the table, while methods such as rename_column and drop_column modify existing columns:

rust
tx.schema()    .alter("users", |table| {        table.integer("votes").default(0);        table.rename_column("bio", "about");        table.drop_column("legacy_flags");    })    .await?;

SQLite cannot perform some alterations in place, such as changing a column type or adding a foreign key. For those operations, dust-framework rebuilds the table automatically while preserving its rows and indexes.

Renaming and dropping tables

Use rename to rename an existing table, and drop or drop_if_exists to remove a table and its data:

rust
tx.schema().rename("posts", "articles").await?;tx.schema().drop("articles").await?;tx.schema().drop_if_exists("drafts").await?;

Calling drop returns an error if the table does not exist, while drop_if_exists succeeds silently. Because renaming a table does not rename its existing indexes or foreign keys (such as posts_user_id_foreign), reference them by their original names if you drop them in a later migration.

Table options

You may configure these table options inside create. MySQL and MariaDB honor all of them, while other databases ignore options they do not support:

Method Effect
table.temporary() Creates a temporary table, which only this database session sees
table.engine("InnoDB") Sets the MySQL and MariaDB storage engine
table.charset("utf8mb4") Sets the MySQL and MariaDB default character set
table.collation("utf8mb4_unicode_ci") Sets the MySQL and MariaDB default collation
table.comment("Blog posts") Adds a comment on PostgreSQL, MySQL, and MariaDB. It works in alter too

Qualified names

A table name may carry a qualifier before a dot, such as "analytics.events". On PostgreSQL that creates the table in another schema, and on MySQL or MariaDB in another database. The qualifier is quoted as its own identifier, so create the schema or database before the migration runs. On SQLite the qualifier names an attached database and defaults to main.

rust
tx.schema()    .create("analytics.events", |table| {        table.id();        table.string("kind");        table.timestamps();    })    .await?;

alter, drop, and rename accept the same qualified form. Keep the qualifier consistent: "analytics.events" and "events" are different names, and a migration that mixes them may create or inspect the wrong table.

Columns

Column types

The schema builder provides methods for adding every common column type to your table blueprint. Unless noted with (), each method accepts the column's name:

Method Column
id() An auto-incrementing big integer primary key named id
increments, big_increments, medium_increments, small_increments, tiny_increments An auto-incrementing integer primary key of that size
integer, big_integer, medium_integer, small_integer, tiny_integer An integer of that size
float, double A floating-point number
decimal(name, total, places) An exact decimal with total digits, places of them after the decimal point
boolean A boolean
char, string Text of up to 255 characters. Set another length with .length(n)
tiny_text, text, medium_text, long_text Longer text. Only MySQL and MariaDB distinguish the sizes
enumeration(name, ["draft", "published"]) Text restricted to the listed allowed values
set(name, values) A MySQL and MariaDB set
json, jsonb A JSON document. Only PostgreSQL distinguishes jsonb
date, time, time_tz A calendar date or a time of day. Only PostgreSQL stores the time zone of time_tz
date_time A wall-clock date and time without a time zone, such as an appointment at 9:00 wherever it takes place
timestamp A moment in time, which dust-framework writes in UTC: timestamp on PostgreSQL, and datetime on MySQL, MariaDB, and SQLite
timestamps() Nullable created_at and updated_at timestamps
soft_deletes() A nullable deleted_at timestamp
year A year
binary Binary data
uuid, ulid A UUID or ULID
foreign_id, foreign_uuid, foreign_ulid A key of another table, ready for a foreign key
ip_address, mac_address A network address, stored as text
geometry, geography A spatial value. PostgreSQL needs the PostGIS extension
vector(name, dimensions) A fixed-length embedding for vector columns
morphs, uuid_morphs, ulid_morphs, and their nullable_ forms {name}_type and {name}_id columns with an index on both
remember_token() A nullable remember_token of 100 characters

Each column decodes into the same Rust type across every supported database, whether you map it onto a model or a db::FromRow struct:

Columns Rust type
id, foreign_id, and the integers i64, or a smaller integer such as i32
float, double f64
decimal dust::numeric::Decimal
boolean bool
char, string, the text types, enumeration, set, and mac_address String
json, jsonb serde_json::Value, or your own type in db::Json<T>
date dust::time::civil::Date
time, time_tz dust::time::civil::Time
timestamps(), soft_deletes(), and the other date and time types dust::time::Timestamp, or civil::DateTime for a wall-clock time
year i32
binary Vec<u8>
uuid, foreign_uuid dust::str::Uuid
ulid, foreign_ulid dust::str::Ulid
ip_address std::net::IpAddr
vector dust::db::Vector

When a column is marked .nullable(), wrap its corresponding Rust field type in Option<T>.

The builder chooses the closest native type each driver has. An enumeration is a native enum on MySQL and MariaDB and a varchar with a check constraint on PostgreSQL and SQLite, so adding an allowed value later means changing the column definition. A uuid is native on PostgreSQL and MariaDB and char(36) on MySQL, while a boolean is tinyint(1) on MySQL and SQLite. The decoder hides these differences: the Rust type in the table above is the same on every driver.

Column modifiers

Columns are NOT NULL by default. Chain column modifiers to customize a column's definition:

rust
tx.schema()    .alter("users", |table| {        table.string("nickname").length(50).nullable().comment("Shown next to posts");    })    .await?;
Modifier Effect
.nullable() Allows NULL
.default(value) Sets a column's default value when omitted on insert
.use_current() Defaults a date or time column to the current time
.use_current_on_update() On MySQL and MariaDB, sets a timestamp to the current time whenever its row changes
.stored_as(expr), .virtual_as(expr) Defines a generated column
.unsigned() Makes an integer unsigned on MySQL and MariaDB
.auto_increment() Makes an integer auto-incrementing, which also makes it the primary key
.starting_value(1000) Sets the first value of an auto-incrementing column on PostgreSQL, MySQL, and MariaDB
.length(n) Sets the length of a string, char, or binary column
.precision(n) Sets the fractional digits of seconds for a time column (overriding the connection's time precision), or sets the bits of a float
.comment(text) Adds a comment on PostgreSQL, MySQL, and MariaDB
.charset(name), .collation(name) Sets a text column's character set on MySQL and MariaDB, or its collation
.after(column), .first() Places a new column on MySQL and MariaDB
.invisible() Leaves the column out of select * on MySQL and MariaDB
.instant(), .lock(Lock::None) On MySQL and MariaDB, alters large tables without copying rows or blocking writes
.primary(), .unique(), .index(), .full_text(), .spatial_index() Adds an index on the column

To place several new columns after a given column on MySQL and MariaDB, add them inside table.after(column, |table| { .. }), where each column is placed immediately after the previous column:

rust
table.after("password", |table| {    table.string("address_line1");    table.string("address_line2").nullable();    table.string("city");});

Defaults

Default values populate a column when an insert omits it. .default accepts either a literal value or a raw expression. Literal values such as 0, false, or "draft" are escaped for the active database, while db::raw! expressions are emitted verbatim:

rust
use dust::db;tx.schema()    .create("flights", |table| {        table.id();        table.string("status").default("scheduled");        table.integer("seats").default(180);        table.boolean("international").default(false);        table.json("movies").default("[]");        table.date("booked_on").default(db::raw!("current_date"));    })    .await?;

A model reads a column's database default when you mark its field #[default].

Generated columns

Generated columns derive their values automatically from other columns in the same row. Pass an expression built with col to stored_as or virtual_as:

rust
use dust::db::col;tx.schema()    .create("line_items", |table| {        table.id();        table.integer("price");        table.integer("quantity");        table.integer("total").stored_as(col("price") * col("quantity"));    })    .await?;

stored_as computes and persists the value whenever a row is inserted or updated. virtual_as computes the value on read and requires PostgreSQL 18 or later when used on PostgreSQL.

Changing columns

To modify an existing column's type or attributes, redefine it inside alter and chain .change():

rust
tx.schema()    .alter("users", |table| {        table.string("name").length(100).nullable().change();    })    .await?;

Because .change() replaces the column's full definition, include every modifier the column should retain. Any modifier you omit is removed; for example, omitting .nullable() changes a nullable column back to NOT NULL.

When changing a column's type on PostgreSQL requires an explicit cast, chain .using(...) to convert existing values:

rust
use dust::db;table.date("birthday").change().using(db::raw!("birthday::date"));

Renaming and dropping columns

Use rename_column and drop_column inside alter to rename or remove existing columns on a table:

rust
tx.schema()    .alter("users", |table| {        table.rename_column("bio", "about");        table.drop_column(["legacy_flags", "legacy_notes"]);    })    .await?;

drop_column accepts either a single column name or a list of names. When you drop a column from a composite index, MySQL and MariaDB can keep the index on the remaining columns. Drop the index first if you want to remove it on every database.

You may also use drop_timestamps, drop_soft_deletes, drop_remember_token, and drop_morphs to remove the columns created by their corresponding helper methods.

Indexes

Creating indexes

Indexes let the database locate matching rows without scanning the entire table, and unique indexes also prevent duplicate values. You may attach an index to a single column with a column modifier, or define composite indexes across multiple columns on the blueprint:

rust
tx.schema()    .create("users", |table| {        table.id();        table.string("email").unique();        table.foreign_id("team_id");        table.timestamps();        table.index(["team_id", "created_at"]);    })    .await?;
Method Index
primary(columns) The primary key
unique(columns) A unique index
index(columns) An index
full_text(columns) A full-text index for db::search, on PostgreSQL, MySQL, and MariaDB
spatial_index(columns) A spatial index, except on SQLite
vector_index(column) Cosine-distance index for vector columns

dust-framework generates index names using the convention {table}_{columns}_{kind}, such as users_email_unique or users_team_id_created_at_index. You can specify a custom name with .name(..):

rust
table.unique(["team_id", "email"]).name("users_team_email_unique");

To choose a specific index algorithm, such as gin for a PostgreSQL jsonb column, chain .algorithm(..):

rust
table.index("attributes").algorithm("gin");

On PostgreSQL, full-text indexes use the english text search configuration by default. To use a different configuration, chain .language("simple") on the index and pass the same language to db::search so queries can use the index.

Renaming and dropping indexes

To drop an index, pass either its explicit name or the list of indexed columns so dust-framework can derive its conventional name:

rust
tx.schema()    .alter("users", |table| {        table.drop_unique(["email"]);        table.drop_index("users_team_id_created_at_index");        table.rename_index("users_name_index", "users_display_name_index");    })    .await?;

Alongside drop_index and drop_unique, the blueprint provides drop_full_text, drop_spatial_index, drop_vector_index, and drop_primary() (which takes no arguments since a table has only one primary key).

Foreign keys

Foreign key constraints enforce referential integrity across tables. Calling constrained infers the referenced table from the column name, so user_id automatically references id on users:

rust
tx.schema()    .create("posts", |table| {        table.id();        table.foreign_id("user_id").constrained().cascade_on_delete();    })    .await?;

Use references to target an explicit table, .column(..) to reference a column other than id, or foreign for composite keys. Chain column modifiers such as .nullable() before constrained or references, since those methods transition the builder to the foreign key constraint:

rust
table.foreign_id("author_id").nullable().references("users").null_on_delete();table.foreign_uuid("team_uuid").references("teams").column("uuid");table.foreign(["order_number"]).references("orders", ["number"]).cascade_on_update();

Configure delete and update actions with these methods:

Method Effect
cascade_on_delete(), cascade_on_update() Deletes the row, or changes its key
restrict_on_delete(), restrict_on_update() Refuses the change
null_on_delete(), null_on_update() Sets the key to NULL
no_action_on_delete(), no_action_on_update() Refuses the change, checked at the end of the statement

dust-framework generates foreign key names using the convention {table}_{columns}_foreign (such as posts_user_id_foreign), or you can specify a custom name with .name(..). You may drop a foreign key by name or by its columns, or call drop_constrained_foreign_id to drop both the constraint and its column in one step:

rust
table.drop_foreign("posts_user_id_foreign");table.drop_foreign(["user_id"]);table.drop_constrained_foreign_id("author_id");

Cascades and deletes

Referential actions run inside the database, not through your models. When a parent row is deleted, cascade_on_delete() removes its children in the same statement, and null_on_delete() clears their keys. Those child rows never become model instances, so model hooks do not run and Deleted events do not fire for them.

That matters in two places:

  • Search indexes. A searchable child removed by a database cascade is not synced. If children are searchable, delete them through their models, or re-import the model after a cascading delete.
  • Application side effects. Auditing, cache invalidation, and notifications tied to model events need the children loaded and deleted individually, or a listener on the parent.

null_on_delete requires a nullable column; declaring it on a NOT NULL foreign key fails when the migration runs. On SQLite, foreign keys enforce these actions only when PRAGMA foreign_keys = ON is enabled on the connection, as the SQLite section describes.

Turning foreign key checks off

When truncating or seeding related tables, foreign key constraints can force an awkward execution order. without_foreign_key_constraints runs your callback inside a transaction with foreign key checks disabled and restores them automatically when the transaction finishes, even if the callback returns an error. Call it on a connection's schema, such as in a seeder or console command:

rust
use dust::db;db::default_connection()?    .schema()    .without_foreign_key_constraints(async |_| {        db::table("posts").truncate().await?;        db::table("users").truncate().await    })    .await?;

On PostgreSQL and SQLite, all foreign key references must be valid again before the transaction commits. SQLite verifies every reference at commit time, while PostgreSQL only defers checks for foreign keys created with .deferrable().

Check constraints

Check constraints enforce a condition on every row written to a table, such as ensuring a product's price is never negative. The database rejects any insert or update that violates the constraint. Build the expression using the query builder condition API:

rust
use dust::db::col;tx.schema()    .create("products", |table| {        table.id();        table.decimal("price", 8, 2);        table.check("products_price_check", col("price").ge(0));    })    .await?;

To remove an existing check constraint, call table.drop_check("products_price_check").

Vector columns

Vector columns store fixed-length embeddings for vector similarity queries. They are supported on PostgreSQL (with the pgvector extension) and MariaDB 11.7 or later. On PostgreSQL, install pgvector on the server, then call ensure_vector_extension to enable it for your database. MariaDB has built-in vector support, so skip that call:

rust
use dust::db::Driver;if tx.driver() == Driver::Postgres {    tx.schema().ensure_vector_extension().await?;}tx.schema()    .create("documents", |table| {        table.id();        table.string("title");        table.vector("embedding", 3).index();    })    .await?;

Use the number of dimensions your embedding model returns. This example uses the three-dimensional embedding from the vector similarity example.

Chaining .index() directly on a vector column automatically creates a cosine-distance vector index (HNSW with vector_cosine_ops on PostgreSQL, or VECTOR INDEX ... DISTANCE=cosine on MariaDB). When adding a vector index to an existing column inside alter, call table.vector_index("embedding") instead of table.index("embedding"). MariaDB supports indexing at most one vector column per table, and the column must be NOT NULL.

Portability notes

Most of the builder is portable: the same migration creates the same table on every driver. A few features exist on only some engines, and a few options are accepted but ignored elsewhere. An unsupported feature fails when the migration runs; an unsupported option is silently left out, because the change still makes sense without it.

Feature or option PostgreSQL MySQL / MariaDB SQLite
full_text index Yes Yes No
spatial_index With PostGIS Yes No
vector column pgvector MariaDB 11.7+ only No
set column No Yes No
jsonb A distinct binary type Same as json Stored as text
enumeration varchar with a check Native enum varchar with a check
.online() index build CREATE INDEX CONCURRENTLY Ignored Ignored
.instant() and .lock(..) Ignored Yes Ignored
.after(), .first(), .invisible() Ignored Yes Ignored
.unsigned() Ignored Yes Ignored
table.comment(..) Yes Yes Ignored

When an ignored option is the difference between a fast change and a table copy, read Changing large tables for the option your production database actually honours.

Changing large tables

A change that completes instantly on a new table can block a busy production table for minutes if the database rewrites rows or locks writes. Each database engine provides specific options to keep tables available during alterations.

On PostgreSQL, creating an index normally blocks writes to the table until the index finishes building. Chain .online() to emit CREATE INDEX CONCURRENTLY so writes can continue. Because PostgreSQL does not allow concurrent index creation inside a transaction, place it in a non-transactional migration that accepts &AnyConnection. Other databases ignore .online():

rust
use dust::db::AnyConnection;pub async fn migrate(db: &AnyConnection) -> dust::Result<()> {    db.schema()        .alter("users", |table| {            table.index("last_seen_at").online();        })        .await}

On MySQL and MariaDB, chaining .instant() adds, modifies, or drops a column by updating only table metadata without copying rows. Chaining .lock(..) on a column, index, or foreign key caps the locking level allowed for the statement: Lock::None permits concurrent reads and writes, while Lock::Shared permits concurrent reads. If the database cannot perform the operation under those constraints, the statement fails instead of copying or locking the table. Other databases ignore both options:

rust
use dust::db::schema::Lock;tx.schema()    .alter("orders", |table| {        table.string("coupon").nullable().instant();        table.index("coupon").lock(Lock::None);    })    .await?;

Inspecting the schema

You may inspect your database's existing tables, columns, and indexes from migrations or console commands:

rust
if !tx.schema().has_table("flights").await? {    // ...}if tx.schema().has_column("users", "email").await? {    // ...}
Method Returns
has_table(table) Whether the table exists
has_column(table, column), has_columns(table, columns) Whether the table has the given column, or all of the given columns
has_index(table, index), has_unique(table, index) Whether the table has an index or unique index with that name or on those columns
has_view(view) Whether the view exists
tables(), views(), types() The database's tables, views, and PostgreSQL types
columns(table), indexes(table), foreign_keys(table) The table's columns, indexes, and foreign keys

Column type names and default expressions are returned in each database engine's native format, so they vary across PostgreSQL, MySQL, MariaDB, and SQLite.

Troubleshooting schema changes

Schema errors come from the database, and the message is usually precise. These are the common ones:

Error Cause Fix
relation "flights" already exists The table was created by an earlier run or migration Guard with has_table, or use drop_if_exists first
column "votes" of relation "users" already exists alter adds columns, so redefining an existing one is a duplicate Chain .change() on the column
cannot drop column ... because other objects depend on it A view, index, or constraint still uses the column Drop the dependent object first
foreign key constraint cannot be implemented The referenced column's type differs, such as uuid against bigint Make both columns the same type
there is no unique constraint matching given keys A foreign key references a column that is not unique Add a unique index, or reference the primary key
Duplicate key name The index already exists, perhaps under the conventional name Use has_index, or drop and recreate it
column ... cannot be cast automatically PostgreSQL needs a conversion for the new type Chain .using(db::raw!("..."))
set is not supported set columns exist only on MySQL and MariaDB Use an enumeration or a JSON column
A MySQL migration left half its changes applied DDL commits the transaction on MySQL and MariaDB Put one table change in each migration

SQLite is the exception to "the database keeps the schema you wrote": some alterations rebuild the table behind the scenes. That rebuild preserves rows and indexes, but it copies them while holding the write lock, so schedule a large SQLite alteration like any other long write.