INSERT builder

Create rows in the users table with ActiveModel and the insert methods

A list page reads rows. A sign-up form creates them. This page covers creating rows: one at a time, several at once, and the case where the row might already exist.

Where this fits

The select page showed how to read rows as models. A model is a finished row, read from the database. An insert starts from the other side, a row that does not exist yet. SeaORM represents that unfinished row with a second struct, the ActiveModel, and this page is about filling it in and saving it.

Smallest working version first

Here is a handler that creates one user from a JSON body and answers with the created user.

use axum::{extract::State, http::StatusCode, Json};
use sea_orm::{entity::prelude::*, DatabaseConnection};
use sea_orm::entity::ActiveValue::{NotSet, Set};
use serde::Deserialize;
use seaorm::user;

#[derive(Deserialize)]
pub struct NewUser {
    pub name: String,
    pub email: String,
}

pub async fn create_user_handler(
    State(db): State<DatabaseConnection>,
    Json(input): Json<NewUser>,
) -> Result<(StatusCode, Json<User>), (StatusCode, String)> {
    let active = user::ActiveModel {
        id: NotSet,
        name: Set(input.name),
        email: Set(input.email),
    };
    let model = active
        .insert(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok((StatusCode::CREATED, Json(User::from(model))))
}

NewUser is a small struct with name and email fields that Axum builds from the request body. The handler turns it into an ActiveModel, inserts it, and returns the saved row with status 201, which means "created".

The next section explains the three unfamiliar parts: ActiveModel, Set and NotSet, and .insert().

The pieces, one at a time

ActiveModel

Every entity has two structs. The Model is a row that already exists. It holds plain values: id: i32, name: String, email: String. The ActiveModel is a row being built. Each of its fields is wrapped in an ActiveValue, which records not just a value but what should happen to that field when the row is saved.

The dense entity from the entities page generates both structs from the one Model definition. You never write the ActiveModel struct by hand. You build one with a struct literal, as above, and SeaORM turns it into SQL.

Set, NotSet, and Unchanged

An ActiveValue is always in one of three states.

  • Set(value) means send this value to the database. Use it for every field the caller supplied.
  • NotSet means leave this field out of the statement entirely. Use it for columns the database fills in itself. In the users table that is id, which the identity sequence fills in, and created_at, which defaults to the current time. Both are left out, and the database supplies them.
  • Unchanged(value) means send this value as it is, without marking the field as changed. It behaves like Set for an insert, because a new row has no old value to compare against. Its real use is in updates, where it tells SeaORM to include the value in the statement without treating the field as edited. It is listed here so the three states are complete, and the update page uses the third one.

Set, NotSet, and Unchanged live in sea_orm::entity::ActiveValue, and the entity prelude does not bring them in, so they need their own import.

use sea_orm::entity::ActiveValue::{NotSet, Set, Unchanged};

The handler above writes them bare, Set(...) and NotSet, because that import is present. Without it, the compiler reports that Set cannot be found, which is easy to misread as a missing dependency. It is only a missing import.

The struct literal needs every field mentioned. There is no shortcut that fills in the rest automatically, unless you add ..Default::default() at the end, which sets every field you did not mention to NotSet. That is the usual way to write it when only one or two fields are set.

use sea_orm::entity::ActiveValue::Set;

let active = user::ActiveModel {
    name: Set(input.name),
    email: Set(input.email),
    ..Default::default()
};

.insert()

.insert(&db) is a method on the ActiveModel, from the ActiveModelTrait trait. It sends the insert and returns the saved row as a Model. It needs ActiveModelTrait in scope, and the entity prelude provides it. Without the prelude, the compiler says insert is an associated function rather than a method, which is its way of saying the trait is missing.

The SQL it builds was checked against the mock database.

INSERT INTO "users" ("name", "email") VALUES ($1, $2)
RETURNING "id", "name", "email"

Only the fields that are Set or Unchanged appear in the column list. id and created_at are absent, so the database fills them in. RETURNING is a Postgres clause that asks the database to send the new row back in the same round trip, which is how .insert() can return a full Model with the generated id already filled in. The values travel as parameters, ["Ada", "ada@example.com"], never pasted into the SQL text.

What .insert() gives back, and what Entity::insert() gives back

There are two spellings of an insert, and they return different things. Do not mix them up.

  • active.insert(&db) returns the inserted row as a Model. Use it when the handler needs to send the new row back, which is the usual case for a create endpoint.
  • user::Entity::insert(active).exec(&db) returns an InsertResult. That struct carries one field, last_insert_id, which is the generated primary key as an i32. Use it when only the new id is needed.

Both send the same SQL. The difference is only what comes back.

The concept behind it

An ActiveModel is a form with three states per field instead of one value per field. That is the whole idea. A plain struct cannot say "leave this column out", because every field always holds some value. The ActiveValue wrapper adds that third option, and the insert builder reads the wrappers to decide which columns belong in the statement.

The same wrapper is what makes updates work later. An update sends only the fields marked Set, and leaves the rest alone. One wrapper serves both statements, which is why the insert and update pages share the same vocabulary.

Why this design

The alternative is writing the INSERT as a SQL string with the values placed by hand. That works, but it has the same two costs as handwritten selects. The column names are invisible to the compiler, and a value has to be placed carefully or a quote breaks the statement.

The ActiveModel removes both costs and adds one more benefit. The database fills in the generated columns, and the RETURNING clause hands the finished row back, so the handler never has to run a second query to learn the new id. The price is the wrapper: every field needs a Set, NotSet, or Unchanged around it, which is more typing than a plain struct literal. The ..Default::default() shorthand keeps that typing short.

A richer example, inserting several rows at once

A bulk import creates many users in one statement instead of one statement per user. insert_many takes a list of active models and sends a single multi-row insert.

use sea_orm::entity::ActiveValue::Set;

pub async fn create_many(
    db: &DatabaseConnection,
    inputs: Vec<NewUser>,
) -> Result<Option<i32>, DbErr> {
    let actives: Vec<user::ActiveModel> = inputs
        .into_iter()
        .map(|input| user::ActiveModel {
            name: Set(input.name),
            email: Set(input.email),
            ..Default::default()
        })
        .collect();
    let result = user::Entity::insert_many(actives).exec(db).await?;
    Ok(result.last_insert_id)
}

Entity::insert_many returns an InsertManyResult, whose last_insert_id is an Option<i32>. It holds the id of the last row inserted, or None when the list was empty. An empty list inserts nothing and does not error, which is worth knowing before you guard against it. The live run in this chapter inserted two users this way and reported the last id as Some(2).

There is also a returning form for many rows. Entity::insert_many(actives).exec_with_returning_many(db) returns every inserted row as a Vec<Model>, and exec_with_returning_keys(db) returns just their ids. The single-row form has the same family. Entity::insert(active).exec_with_returning(db) returns the one inserted model, which is the same result as active.insert(&db) through a different spelling.

Variations

When the row might already exist

email is unique, so inserting a user whose email is already in the table fails. The failure is a database error with Postgres code 23505, and its message names the constraint: duplicate key value violates unique constraint "users_email_key". The handler sees it as a DbErr::Query, because the insert uses RETURNING and the failure happens while fetching the returned row.

Sometimes a clash is not an error. A sync job that re-sends the same users wants the second insert to update the name instead of failing. That is an upsert, and SeaORM spells it with on_conflict.

use sea_orm::entity::ActiveValue::Set;
use sea_query::OnConflict;

let active = user::ActiveModel {
    name: Set("Ada Lovelace".to_owned()),
    email: Set("ada@example.com".to_owned()),
    ..Default::default()
};
let result = user::Entity::insert(active)
    .on_conflict(
        OnConflict::column(user::Column::Email)
            .update_column(user::Column::Name)
            .to_owned(),
    )
    .exec(&db)
    .await?;

OnConflict::column(...) names the column whose unique constraint may clash, and .update_column(...) names the column to overwrite with the new value. The SQL it builds is INSERT INTO "users" ("name", "email") VALUES ($1, $2) ON CONFLICT ("email") DO UPDATE SET "name" = "excluded"."name", where excluded is Postgres for the row that was proposed. OnConflict comes from the sea-query crate, so it needs its own import. This shape was checked against the mock database, which confirmed the ON CONFLICT clause is present.

Inserting only if the row is new

The other answer to a clash is to skip the row quietly. on_conflict_do_nothing_on does that for a named column, and it returns a TryInsert instead of an Insert, whose result tells you what happened.

use sea_orm::entity::ActiveValue::Set;
use sea_orm::TryInsertResult;

let active = user::ActiveModel {
    name: Set("Ada".to_owned()),
    email: Set("ada@example.com".to_owned()),
    ..Default::default()
};
let outcome = user::Entity::insert(active)
    .on_conflict_do_nothing_on([user::Column::Email])
    .exec(&db)
    .await?;
match outcome {
    TryInsertResult::Inserted(result) => println!("inserted id {}", result.last_insert_id),
    TryInsertResult::Conflicted => println!("already there, skipped"),
    TryInsertResult::Empty => println!("nothing to insert"),
}

Inserted carries the usual InsertResult. Conflicted means the row clashed and nothing was inserted, and it is not an error. Empty means the insert list was empty. The plain on_conflict_do_nothing() without a column list does the same thing for a clash on the primary key. The mock test for this page confirms the Conflicted outcome: when the mock returns no row, the result is Conflicted, not an error.

How the pieces connect

HTTP POST with JSON body
    |
    v
Axum builds NewUser from the body
    |
    v
Handler builds ActiveModel
    name: Set(...)    email: Set(...)
    id: NotSet        created_at: not mapped
    |
    v
active.insert(&db)  -- or Entity::insert(active).exec(&db)
    |
    v
INSERT ... VALUES ($1, $2) RETURNING "id", "name", "email"
    |
    v
Postgres fills id and created_at, returns the new row
    |
    v
Handler converts the Model to a User, answers 201

The handler never writes SQL. It fills in a form, and the database fills in the rest.

Testing

Inserts are easy to test without a database, because the mock database records the SQL and hands back a canned row. The mock lives behind the mock feature of the sea-orm dependency.

sea-orm = { version = "2.0.4", features = ["sqlx-postgres", "runtime-tokio-rustls", "macros", "mock"] }

A test queues the row the mock should return, runs the insert, and checks the recorded SQL.

use sea_orm::{DatabaseBackend, DbErr, MockDatabase};
use sea_orm::entity::ActiveValue::{NotSet, Set};

#[tokio::test]
async fn insert_sends_only_set_columns() -> Result<(), DbErr> {
    let db = MockDatabase::new(DatabaseBackend::Postgres)
        .append_query_results(vec![vec![user::Model {
            id: 1,
            name: "Ada".to_owned(),
            email: "ada@example.com".to_owned(),
        }]])
        .into_connection();
    let active = user::ActiveModel {
        id: NotSet,
        name: Set("Ada".to_owned()),
        email: Set("ada@example.com".to_owned()),
    };
    let model = active.insert(&db).await?;
    assert_eq!(model.id, 1);
    let log = db.into_transaction_log();
    assert_eq!(log.len(), 1);
    Ok(())
}

The mock checks in this chapter's scratch project confirm the insert SQL shown above, that Unchanged columns are sent while NotSet columns are left out, that the upsert builds an ON CONFLICT clause, that exec_with_returning hands back the model, and that a do-nothing insert reports Conflicted instead of erroring.

The same inserts were also run against a real Postgres 16 database. The live run created Ada with id 1, inserted two more users at once and reported the last id as Some(2), and inserting a duplicate email failed with the 23505 unique-violation error quoted above.

Common beginner mistakes

Leaving a required field NotSet

// Wrong. name is NOT NULL and has no default, so the database
// rejects the row. The insert fails at Postgres, not at compile time.
let active = user::ActiveModel {
    email: Set("ada@example.com".to_owned()),
    ..Default::default()
};
// Right. Every NOT NULL column without a default needs a Set.
let active = user::ActiveModel {
    name: Set("Ada".to_owned()),
    email: Set("ada@example.com".to_owned()),
    ..Default::default()
};

..Default::default() sets everything unmentioned to NotSet, which is correct for id and wrong for name. The compiler cannot catch this, because NotSet is a legal state for every field. The database is the one that complains.

Setting the id by hand

// Wrong. The id comes from the identity sequence. Setting it yourself
// either collides with an existing row or fights the sequence.
let active = user::ActiveModel {
    id: Set(1),
    name: Set("Ada".to_owned()),
    email: Set("ada@example.com".to_owned()),
};
// Right. Leave the id NotSet and read it back from the returned model.
let active = user::ActiveModel {
    id: NotSet,
    name: Set("Ada".to_owned()),
    email: Set("ada@example.com".to_owned()),
};

There are rare cases where an id is set on purpose, such as restoring a backup. Ordinary creates are not one of them.

Using the Model to insert

// Wrong. Model has no insert method. Inserting is an ActiveModel job.
let model = user::Model { id: 0, name: "Ada".to_owned(), email: "ada@example.com".to_owned() };
let saved = model.insert(&db).await?;
// Right. Build an ActiveModel and insert that.
let active = user::ActiveModel {
    name: Set("Ada".to_owned()),
    email: Set("ada@example.com".to_owned()),
    ..Default::default()
};
let saved = active.insert(&db).await?;

A Model is a row that already exists. To make a new row, start from an ActiveModel. Converting a Model into an ActiveModel is possible with IntoActiveModel, but it is a detour for a create endpoint that starts from request data.

Expecting Entity::insert().exec() to return the model

// Wrong. exec() returns an InsertResult, which has only last_insert_id.
// There is no model to convert here.
let result = user::Entity::insert(active).exec(&db).await?;
let saved = User::from(result);
// Right. Use active.insert() when the handler needs the saved row.
let model = active.insert(&db).await?;
let saved = User::from(model);

Or use Entity::insert(active).exec_with_returning(&db), which returns the model. The two spellings exist for different needs, and picking the wrong one is a type error the compiler catches at once.

Returning DbErr from a handler

// Wrong. DbErr has no IntoResponse implementation, so Axum cannot
// turn it into a response and the handler does not compile.
pub async fn create_user_handler(
    State(db): State<DatabaseConnection>,
    Json(input): Json<NewUser>,
) -> Result<(StatusCode, Json<User>), DbErr> {
    // ...
}
// Right. Map the error into a status and a message first.
pub async fn create_user_handler(
    State(db): State<DatabaseConnection>,
    Json(input): Json<NewUser>,
) -> Result<(StatusCode, Json<User>), (StatusCode, String)> {
    let model = active
        .insert(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    // ...
}

DbErr is a fine error type for plain functions. Handlers need a response, so the error must be mapped before it leaves the handler.

Final complete example

Here is the create handler and a bulk create handler together in one file, wired into a router. The shapes here are the ones the mock tests and the live run checked.

use axum::{
    extract::State,
    http::StatusCode,
    routing::post,
    Json, Router,
};
use sea_orm::{entity::prelude::*, DatabaseConnection};
use sea_orm::entity::ActiveValue::Set;
use serde::Deserialize;
use seaorm::user;

#[derive(Deserialize)]
pub struct NewUser {
    pub name: String,
    pub email: String,
}

pub async fn create_user_handler(
    State(db): State<DatabaseConnection>,
    Json(input): Json<NewUser>,
) -> Result<(StatusCode, Json<User>), (StatusCode, String)> {
    let active = user::ActiveModel {
        name: Set(input.name),
        email: Set(input.email),
        ..Default::default()
    };
    let model = active
        .insert(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok((StatusCode::CREATED, Json(User::from(model))))
}

pub async fn create_many_handler(
    State(db): State<DatabaseConnection>,
    Json(inputs): Json<Vec<NewUser>>,
) -> Result<(StatusCode, Json<Vec<User>>), (StatusCode, String)> {
    let actives: Vec<user::ActiveModel> = inputs
        .into_iter()
        .map(|input| user::ActiveModel {
            name: Set(input.name),
            email: Set(input.email),
            ..Default::default()
        })
        .collect();
    let models = user::Entity::insert_many(actives)
        .exec_with_returning_many(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok((
        StatusCode::CREATED,
        Json(models.into_iter().map(User::from).collect()),
    ))
}

pub fn users_router(db: DatabaseConnection) -> Router {
    Router::new()
        .route("/users", post(create_user_handler))
        .route("/users/bulk", post(create_many_handler))
        .with_state(db)
}

Json<Vec<NewUser>> reads a JSON array of users from the request body, so the bulk endpoint takes the same shape repeated. exec_with_returning_many sends one multi-row insert and returns every saved row, so the handler can answer 201 with the full list, ids included.

Summary

An insert starts with an ActiveModel, where every field carries one of three states. Set sends a value, NotSet leaves the column out for the database to fill in, and Unchanged sends a value without marking it changed. .insert() saves one row and hands back the finished model, using RETURNING so the generated id comes back in the same round trip. insert_many saves a list in one statement, and its result carries the last id or None when the list was empty. A clash on the unique email either fails with a 23505 error, updates the row with on_conflict, or skips it quietly with on_conflict_do_nothing_on and a TryInsertResult that says what happened. The pattern to carry forward is small. Build the row as an ActiveModel, send it with one awaited call, map the error into a response, and return the saved row. The next operation keeps the same ActiveModel and the same three states, but points them at a row that already exists.