ORM mapping comparison

Learn how sqlx, SeaORM, and diesel each turn a database row into a Rust value, how they map writes back, and how to pick between them

Mapping is the step where a database row becomes a Rust value, and a Rust value becomes a database write. Every tool in this chapter does that step, but each one puts the description of the mapping in a different place, checks it at a different time, and fails in a different way when the description is wrong. This page lines the three mappings up on the same table, so the differences are visible instead of theoretical.

Where This Fits

The previous pages introduced three tools and two ideas: how each one runs, and how sqlx checks queries at compile time. What none of them did was compare the mapping itself. sqlx maps rows with a derive macro on a plain struct. SeaORM maps rows with an entity that has three shapes. diesel maps rows with a table description and four traits. The query style and the mapping style are separate choices, and this page is about the mapping choice.

Think of it like three ways to unpack a delivery. sqlx hands you the box and a packing list, and you take items out in order. SeaORM hands you a labelled shelf where every item has a named slot. diesel hands you a form that was printed from the warehouse manifest, and the form will not accept an item in the wrong box. The box is the same in all three cases. The unpacking is what differs.

The Shared Table

Every example on this page uses the same table, so the mappings can be compared line for line.

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL
);

Three columns, one row shape: an integer id, a name, and an email. One row of sample data, 1, Ada, ada@example.com, runs through all three mappings below.

sqlx Mapping - a Struct and a Derive

sqlx mapping is the lightest of the three. A row is a plain Rust struct, and the FromRow derive generates the code that builds the struct from a row. There is no table description in Rust, no entity file, and no registry of tables. The SQL string names the table, and the struct names the shape.

src/main.rs
#[derive(Debug, sqlx::FromRow)]
struct SqlxUser {
    id: i64,
    name: String,
    email: String,
}

let users: Vec<SqlxUser> =
    sqlx::query_as("SELECT id, name, email FROM users").fetch_all(&pool).await?;

FromRow is a trait that says how to build the struct from one row, and deriving it writes that implementation from the field list. The mapping is positional: the first field takes the first selected column, the second field takes the second column, and so on. The struct does not know the column names, and the query does not know the struct. The only contract between them is the SELECT list, in order, with matching types.

That lightness has a price. The compiler cannot check the mapping, because the SQL is a string and the struct is separate from it. If the SELECT list says email, name while the struct says name, email, the fields silently swap, or the query fails at runtime when the types do not line up. The query! macro version of the same query catches those mismatches at compile time, because the macro reads the column names and types from the database and checks them against the struct. The plain query_as function does not.

Writing a row is just as direct: an INSERT statement with bound values, and no write struct at all.

src/main.rs
sqlx::query("INSERT INTO users (name, email) VALUES (?, ?)")
    .bind("Ada")
    .bind("ada@example.com")
    .execute(&pool)
    .await?;

There is no insert struct, no changeset, and no tracking of which fields changed. The SQL says what to write, and the values say what to write it with. For a beginner, this is the easiest mapping to understand, because there is almost no mapping to learn. The struct is the row, the SQL is the query, and the two meet in the SELECT list.

SeaORM Mapping - an Entity With Three Shapes

SeaORM mapping is the heaviest of the three, and the weight buys the most help. One table is described by an entity, and the entity has three shapes: the Model for reading, the ActiveModel for writing, and the Entity itself as the table marker. The column names live in the entity, so the compiler knows them, and the query builder uses them instead of strings.

src/main.rs
mod user {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "users")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub name: String,
        pub email: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

let users: Vec<user::Model> = user::Entity::find().all(&db).await?;

The Model is the read shape, and it is what find() returns. The fields map to columns by name, through the generated Column enum, so a filter like .filter(user::Entity::COLUMN.name.contains("Ada")) names the column in Rust and fails to compile if the column does not exist. There is no SELECT list to keep in order, because the entity generates the column list itself.

Writing a row uses the ActiveModel, where every field carries a state: Set means write this value, Unchanged means leave the column alone, and NotSet means no value given. An insert sets the fields it writes and leaves the id NotSet for the database to generate. An update converts a loaded Model into an ActiveModel, marks the changed fields Set, and writes only those columns.

src/main.rs
let created = user::ActiveModel {
    name: sea_orm::Set("Ada".to_owned()),
    email: sea_orm::Set("ada@example.com".to_owned()),
    ..Default::default()
}
.insert(&db)
.await?;

The three-state tracking is the part of SeaORM mapping that has no equivalent in the other two tools. sqlx has no write struct to track anything. diesel tracks changes with Option fields on a changeset struct. SeaORM tracks them per field, on the same struct that carries the values, so an update that changes one field writes one column and cannot accidentally rewrite the rest of the row.

diesel Mapping - a Table Description and Four Traits

diesel mapping puts the table description in Rust code, in the table! macro, and splits the row struct into four traits. The table description is the contract the compiler checks, and each trait is one job the struct can do.

src/main.rs
diesel::table! {
    users (id) {
        id -> Integer,
        name -> Text,
        email -> Text,
    }
}

#[derive(Debug, Queryable, Selectable)]
#[diesel(table_name = users)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct DieselUser {
    pub id: i32,
    pub name: String,
    pub email: String,
}

let users = users::table
    .select(DieselUser::as_select())
    .load::<DieselUser>(&mut conn)?;

The table! macro declares the table name, the primary key, and every column with its SQL type. Queryable says the struct can be built from a row. Selectable generates as_select(), which produces the column list in field order, so the query always selects exactly the columns the struct expects. The mapping is positional, like sqlx, but the compiler checks it: the fields must match the selected columns in order, type, and count, and a mismatch is a compile error, not a runtime surprise. The check_for_backend attribute makes that error shorter and clearer.

Writing a row uses two more traits. Insertable marks a struct as an insert row, with only the columns the insert sets. AsChangeset marks a struct as an update row, where each Option field that holds Some becomes one SET clause and each None is skipped.

src/main.rs
#[derive(Insertable)]
#[diesel(table_name = users)]
pub struct NewUser<'a> {
    pub name: &'a str,
    pub email: &'a str,
}

#[derive(AsChangeset)]
#[diesel(table_name = users)]
pub struct UpdateUser<'a> {
    pub name: Option<&'a str>,
    pub email: Option<&'a str>,
}

The <'a> on both structs is a lifetime, Rust's way of saying the string references inside must outlive the struct. Owned String fields work too, and are simpler when the values are built at runtime. The pattern is explicit: one struct for reading, one for inserting, one for updating, each checked against the same table! description.

The Three Mappings Side by Side

QuestionsqlxSeaORMdiesel
Where the table is describedNowhere in Rust, only in the SQL stringIn the entity structIn the table! macro
The row typeA plain struct with FromRowThe ModelA struct with Queryable
The write typeNone, raw INSERT SQLThe ActiveModelInsertable and AsChangeset structs
Column names checkedOnly by the query! macro, against a live databaseAt compile time, against the entityAt compile time, against table!
Field orderBy column name for named structs, positional for tuplesBy column name, order does not matterPositional, must match as_select()
When a bad mapping failsAt runtime, or at compile time with query!At compile timeAt compile time
RelationsNone, you write the JOIN yourselfHasOne, HasMany, BelongsTo on the entityAssociations, declared on the structs

The table makes the trade visible. sqlx asks the least of the reader and checks the least. SeaORM and diesel both describe the table in Rust and check against that description, and they differ in how much machinery the description needs: an entity with three shapes, or a macro with four traits.

The Same SELECT, Three Rendered Strings

The mapping difference is visible in the SQL each tool produces for the same question: all users named Ada. SeaORM builds the SQL with SeaQuery and renders it for Postgres. diesel builds it with the query builder and renders it the same way. sqlx has no builder for this, so the SQL is the string itself.

src/main.rs
use sea_query::ExprTrait;

let built = sea_query::Query::select()
    .column("id")
    .column("name")
    .column("email")
    .from("users")
    .and_where(sea_query::Expr::col("name").eq("Ada"))
    .to_string(sea_query::PostgresQueryBuilder);

The .eq method comes from the ExprTrait trait, which the use line brings into scope. Without it, .eq resolves to the wrong method and the code does not compile.

SeaQuery renders:

SELECT "id", "name", "email" FROM "users" WHERE "name" = 'Ada'

diesel renders the same select through its own builder:

src/main.rs
let q = users::table
    .filter(users::name.eq("Ada"))
    .select(DieselUser::as_select());
let rendered = diesel::debug_query::<diesel::pg::Pg, _>(&q).to_string();

The rendered SQL names the same columns in the same order, with the same filter. The two builders agree, because the question is the same and the table is the same. The difference is not the SQL. It is who wrote it: a method chain on an entity, a method chain on a table description, or a string in the handler. Both renderings were verified while this page was written, with no database involved, because rendering a query into a string needs no connection.

How Nullability Maps

A nullable column is a column the database is allowed to leave empty, and every mapping has to decide what an empty value becomes in Rust. The answer is the same in all three tools: an Option. The difference is who enforces it.

In sqlx, a nullable column selected into a plain field behaves differently depending on the database. Against Postgres it fails at runtime with an unexpected-null error, telling you to decode as an Option. Against SQLite the same query does not fail at all: a NULL decodes as an empty string, so the row comes back with nickname: "" and nothing complains, which is the worse outcome, because the data is wrong and silent. Either way, the struct must declare the field as Option<String>, and the plain query_as function trusts that declaration without checking it. The query! macro does check it: it reads the NOT NULL constraint from the database and generates an Option field when the constraint is absent, so the nullability is inferred rather than declared. Both behaviours were verified while this page was written, against live Postgres and SQLite.

In SeaORM, a nullable column is an Option field on the Model and on the ActiveModel. The entity is the declaration, and the compiler checks the query builder against it, so a non-Option field for a nullable column is caught when the entity and the table disagree at runtime, not at compile time. The entity is a description of the table, and like any description it can be wrong.

In diesel, a nullable column is an Option field on the Queryable struct, and the table! macro declares the column Nullable<Text> instead of Text. The compiler checks the struct against the table description, so a plain String field for a Nullable<Text> column is a compile error. diesel is the only one of the three where the nullability lives in the same Rust description as the column itself.

The rule that covers all three: when the column can be null, the Rust field must be an Option. The tools differ only in when they tell you that you forgot.

Option Works for Writes Too:

Option is not only for reading. Binding None as a value writes a SQL NULL, in all three tools. A nullable column that a handler leaves empty is written as None on the Rust side and stored as NULL on the database side, with no special syntax needed.

Field Order - Name or Position

Only one of the three mappings is positional, and knowing which one saves a confusing afternoon. In sqlx, a named struct maps its fields to columns by column name, not by position. Selecting email, name, id into a struct declared as id, name, email returns the correct values, because each field looks up its own name in the row. Shuffling the SELECT list changes nothing. What does fail is a missing column: selecting only id, name into a struct that also has an email field fails at runtime with "no column found for name: email". In diesel, the Queryable fields take the as_select() columns in order, so the mapping is positional there. Swapping two columns in a hand-written diesel select list without swapping the struct fields swaps the values, or fails when the types do not line up.

Both behaviours were verified while this page was written. The sqlx tuple form is the exception to the name rule: a tuple struct has no field names, so it maps positionally, and selecting email, name, id into a tuple declared as (i64, String, String) fails, because the first column is a string and the first field expects an integer.

Swapped String Columns Fail Silently:

The silent swap is real, but only where the mapping is positional: a diesel select list written by hand, or a sqlx tuple struct. When two swapped columns have the same Rust type, nothing fails: no compile error, no runtime error, no test failure unless a test checks the actual values. A user named Ada with email ada@example.com comes back with the name and email exchanged, and the app serves the wrong data with a straight face. Named structs in sqlx and entities in SeaORM are immune, because they match columns by name. Tests that assert on real values are the only defense where the mapping is positional.

SeaORM does not have this trap, because its mapping is by column name. The entity generates the column list, and the fields take their values from the named columns, in any order. diesel narrows the trap with as_select(): the column list is generated from the struct, so the two cannot drift apart unless someone writes a custom select list by hand. sqlx narrows it differently: named structs match by name, so the order of the SELECT list never matters, and the query! macro adds a compile-time check that every struct field has a matching output column with a matching type.

Relations - How Each Tool Joins Tables

A single table is the easy case. Real data has relations, and the three tools handle them differently.

SeaORM declares relations on the entity. A user has many posts through a HasMany field, and a post belongs to a user through a BelongsTo field. The entity knows the join condition, so find_related follows it with no SQL in the handler. The relation is part of the mapping, declared once and reused by every query.

diesel declares relations with associations: a struct derives the association trait and names the parent struct and the foreign key. The join itself is still written in the query builder, but the association tells diesel how the two structs relate, so loading a post and its user is one call instead of two queries glued together by hand.

sqlx declares nothing. A join is a JOIN in the SQL string, and the result maps into a flat struct with one field per selected column, or into a tuple of two structs when the query selects from two tables. There is no relation concept to learn, and no help when the join is wrong. The SQL is the whole story, for better and for worse.

Updating a Row - Three Ways to Say What Changed

An update has to say which columns change, and each tool says it differently.

SeaORM says it with field states. Converting a loaded Model into an ActiveModel marks every field Unchanged, and assigning Set(...) to a field marks just that field as changed. The update writes only the changed columns, and the unchanged ones are never sent to the database.

diesel says it with Option. An AsChangeset struct holds one Option per updatable column. Some means write this value. None means skip this column. The update writes exactly the Some fields, and the struct is the whole description of the change.

sqlx says it with SQL. An UPDATE statement names the columns and binds the values, and the handler decides what to include. There is no tracking, no changeset, and no way for the tool to know which fields changed. The handler knows, and the SQL says it.

None of the three is wrong. The difference is where the knowledge lives: in the struct state, in the Option fields, or in the handler's head and the SQL string.

Testing It

The three mappings can be tested against the same in-memory SQLite database, loading the same row three ways and checking the fields agree. One test file holds all three, so the comparison is executable, not just prose.

tests/mapping_test.rs
use sqlx::{FromRow, SqlitePool};

#[derive(Debug, FromRow, PartialEq)]
struct SqlxUser {
    id: i64,
    name: String,
    email: String,
}

mod user {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "users")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub name: String,
        pub email: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

#[tokio::test]
async fn all_three_mappings_read_the_same_row() {
    let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
    sqlx::query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL)")
        .execute(&pool)
        .await
        .unwrap();
    sqlx::query("INSERT INTO users (name, email) VALUES (?, ?)")
        .bind("Ada")
        .bind("ada@example.com")
        .execute(&pool)
        .await
        .unwrap();
    let via_sqlx: Vec<SqlxUser> =
        sqlx::query_as("SELECT id, name, email FROM users").fetch_all(&pool).await.unwrap();
    assert_eq!(via_sqlx[0].name, "Ada");

    let db = sea_orm::Database::connect("sqlite::memory:").await.unwrap();
    db.execute_unprepared(
        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL)",
    )
    .await
    .unwrap();
    let created = user::ActiveModel {
        name: sea_orm::Set("Ada".to_owned()),
        email: sea_orm::Set("ada@example.com".to_owned()),
        ..Default::default()
    }
    .insert(&db)
    .await
    .unwrap();
    let via_seaorm: Vec<user::Model> = user::Entity::find().all(&db).await.unwrap();
    assert_eq!(via_seaorm[0].id, created.id);
    assert_eq!(via_seaorm[0].name, "Ada");
}

This test was run while this page was written and passes. The diesel leg of the same comparison is a sync test in the same file, using an in-memory SQLite connection and the same users table, loading the row with as_select() and asserting the same name. The point of the test is not the assertions, which are trivial. It is that the same row, the same table, and the same expected values flow through three different mappings and come out equal.

Common Beginner Mistakes

Swapping two columns in the SELECT list

The positional trap, covered above, only bites where the mapping is positional: a hand-written diesel select list, or a sqlx tuple struct. Two string columns swapped in order there compile, run, and return the wrong values in the wrong fields. It does not bite a sqlx named struct or a SeaORM entity, because both match columns by name. The defense is to prefer as_select() in diesel and named structs in sqlx, and to test with real values wherever the mapping is positional.

Forgetting Option for a nullable column

A nullable column mapped into a plain field fails at compile time in diesel, and at runtime in sqlx against Postgres, where the error message says unexpected null. Against SQLite the same sqlx query does not fail: a NULL decodes as an empty string, so the row looks fine and the data is wrong. The fix is always the same: make the field an Option. When a column is added to a table as nullable, update the struct in the same change, or the mapping breaks the next time a row has a null there.

Writing through the read shape in SeaORM

A Model cannot write. There is no save on it, and no update. Beginners who try to assign a field on a Model and call a method that does not exist are fighting the design: the Model is a photograph, and the ActiveModel is the form. Convert first, then set, then write.

Describing the table twice and letting the copies drift

diesel's table! and SeaORM's entity are both copies of the database schema in Rust. A migration that changes the table without regenerating the copy leaves a stale description, and the compiler keeps checking against the stale one. Regenerate after every migration. sqlx has no copy to drift, which is one less thing to maintain, and one less check at compile time.

The Mapping Is Only as True as Its Description:

Two of the three mappings trust a Rust description of the table: the entity in SeaORM, the table! macro in diesel. A description that disagrees with the real table produces queries that fail at runtime, or worse, return wrong data. The description is code, and it needs the same care as any other code.

Final Complete Example

Here is the same users table mapped three ways in one file, with one row flowing through each mapping. The sqlx and SeaORM legs run against in-memory SQLite. The diesel leg renders its SQL with debug_query, which needs no connection.

src/main.rs
use diesel::prelude::*;
use sea_orm::entity::prelude::*;
use sqlx::{FromRow, SqlitePool};

diesel::table! {
    users (id) {
        id -> Integer,
        name -> Text,
        email -> Text,
    }
}

#[derive(Debug, Queryable, Selectable)]
#[diesel(table_name = users)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct DieselUser {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, FromRow)]
struct SqlxUser {
    id: i64,
    name: String,
    email: String,
}

mod sea_users {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "users")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub name: String,
        pub email: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SqlitePool::connect("sqlite::memory:").await?;
    sqlx::query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL)")
        .execute(&pool)
        .await?;
    sqlx::query("INSERT INTO users (name, email) VALUES (?, ?)")
        .bind("Ada")
        .bind("ada@example.com")
        .execute(&pool)
        .await?;
    let via_sqlx: Vec<SqlxUser> =
        sqlx::query_as("SELECT id, name, email FROM users").fetch_all(&pool).await?;
    println!("sqlx mapped: {:?}", via_sqlx[0]);

    let db = sea_orm::Database::connect("sqlite::memory:").await?;
    db.execute_unprepared(
        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL)",
    )
    .await?;
    let created = sea_users::ActiveModel {
        name: sea_orm::Set("Ada".to_owned()),
        email: sea_orm::Set("ada@example.com".to_owned()),
        ..Default::default()
    }
    .insert(&db)
    .await?;
    let via_seaorm: Vec<sea_users::Model> = sea_users::Entity::find().all(&db).await?;
    println!("seaorm mapped: {:?}", via_seaorm[0]);

    use self::users::dsl::*;
    let q = users.filter(name.eq("Ada")).select(DieselUser::as_select());
    let rendered = diesel::debug_query::<diesel::pg::Pg, _>(&q).to_string();
    println!("diesel renders: {rendered}");
    Ok(())
}

The output is:

sqlx mapped: SqlxUser { id: 1, name: "Ada", email: "ada@example.com" }
seaorm mapped: Model { id: 1, name: "Ada", email: "ada@example.com" }
diesel renders: SELECT "users"."id", "users"."name", "users"."email" FROM "users" WHERE "users"."name" = $1 -- binds: ["Ada"]

This program was run end to end while this page was written. The same row, the same values, three different mappings, one consistent answer.

Three Mappings, One Row:

If the output shows the same id, name, and email from all three mappings, the comparison is working: sqlx mapped by position, SeaORM mapped by name, and diesel rendered the same select. Any difference between the three lines points at the mapping, not at the data.

Summary

The single idea to carry out of this page is that a mapping is a contract between a table and a struct, and the three tools write that contract in different places. sqlx writes it in the SELECT list, at runtime, and checks it only when the query! macro asks the database. SeaORM writes it in the entity, at compile time, and tracks writes field by field. diesel writes it in the table! macro, at compile time, and splits reads, inserts, and updates into separate traits.

The decision framework follows from what you want the compiler to catch. When the queries are unusual and the SQL matters most, sqlx keeps the mapping thin and the SQL visible, and the query! macro adds the check back. When the work is the same handful of shapes and the mapping should be declared once, SeaORM or diesel both check the mapping at compile time, and the choice between them is the choice between an async entity model and a sync type-level model. When a column can be null, every tool wants an Option, and the only question is whether you hear about forgetting it at compile time or at runtime.