DELETE builder

Remove rows from the users table with model delete and delete many

Deleting is the last of the four write operations, and the most dangerous. An insert that fails leaves nothing behind. A delete that goes wrong removes data that cannot be put back. SeaORM makes the shape of a delete look like the shape of a select, so the same filter that finds the rows also limits the damage.

Where this fits

The select page found rows, the insert page made them, and the update page changed them. This page removes them. A delete handler follows the same read-first pattern as the update handler: read the row, answer 404 when it is not there, then delete it. The bulk form follows the same filter pattern as the select and update pages.

Smallest working version first

Here is a handler that deletes one user by id.

use axum::{
    extract::{Path, State},
    http::StatusCode,
    Json,
};
use sea_orm::{entity::prelude::*, DatabaseConnection};
use seaorm::user;

pub async fn delete_user_handler(
    State(db): State<DatabaseConnection>,
    Path(id): Path<i32>,
) -> Result<StatusCode, (StatusCode, String)> {
    let found = user::Entity::find_by_id(id)
        .one(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "user not found".to_string()))?;
    found
        .delete(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok(StatusCode::NO_CONTENT)
}

The handler reads the row first, so a missing id answers 404. Then found.delete(&db) removes it. The answer is status 204, which means the request succeeded and there is no body to send back, because the row is gone and there is nothing left to return.

The pieces, one at a time

Model::delete()

.delete(&db) is a method on the Model, from the ModelTrait trait, which the entity prelude provides. It deletes the row the model came from, matching on the primary key, and returns a DeleteResult. That struct carries one field, rows_affected, which says how many rows were removed.

The SQL it builds was checked against the mock database.

DELETE FROM "users" WHERE "users"."id" = $1

There is no RETURNING clause and no row comes back. A delete returns a count, not the deleted row. When the handler needs the deleted user's details in its response, it must read them from the model before deleting, because after the delete there is nothing to read.

The read first, and why it matters twice

The read does two jobs. It produces the 404, and it produces the model that .delete() needs. A delete without the read would need the id wrapped in a form instead, and a typo in the form would delete the wrong row or fail with a missing-key error. The read-first pattern keeps the delete tied to a row the handler has actually seen.

There is a second reason, and it is about the answer. A delete that returns 204 says "the row is gone". A delete on a missing id must say something else, and the only way to know the id was missing is to look first. Deleting is the one operation where the absence of a row is not an error from the database: DELETE on a missing row succeeds and reports zero rows affected. The handler has to check for itself, and the read is where it checks.

DeleteResult

Every delete returns a DeleteResult, whether it removes one row or many. Its rows_affected field is a u64. For a single delete it is 0 or 1. For a bulk delete it is however many rows matched. A handler that needs to know whether anything was deleted reads this field. The database does not raise an error for a delete that matches nothing, so the count is the only signal.

The concept behind it

A delete is a select that removes instead of returning. The WHERE clause is the same, the filter vocabulary is the same, and the danger is the same in reverse. A select with a missing filter returns too much. A delete with a missing filter removes too much. SeaORM keeps the two operations in the same shape on purpose, so the habit of scoping a query with a filter carries over to the operation where scoping matters most.

The single delete scopes itself. It matches on the primary key of a model the handler has already read, so the WHERE clause is built from a real row, not from a value the handler typed. The bulk delete does not scope itself. It deletes exactly what its filters describe, and with no filters it deletes the whole table. That asymmetry is the whole page in one sentence: single deletes are safe by construction, bulk deletes are safe by discipline.

Why this design

The alternative is writing the DELETE as a SQL string. That works, and the statement is short, but it has the same cost as handwritten selects and updates. The table and column names are invisible to the compiler, and the WHERE clause is one forgotten condition away from a table wipe.

The builder does not remove the danger. A bulk delete with no filter still removes every row. What it removes is the accidental version of the danger: a misspelled column becomes a compile error, a value travels as a parameter, and the filter methods are the same ones the reader already uses for selects, so the shape of a careful delete is familiar before it is written.

A richer example, deleting every matching user at once

A cleanup job deletes every user whose name starts with Test, in one statement, without loading any rows.

pub async fn delete_test_users(db: &DatabaseConnection) -> Result<u64, DbErr> {
    let result = user::Entity::delete_many()
        .filter(user::Column::Name.like("Test%"))
        .exec(db)
        .await?;
    Ok(result.rows_affected)
}

Entity::delete_many() starts a delete with no conditions. .filter() adds the WHERE clause, using the same Column comparisons as the select page. .exec() runs it and returns a DeleteResult. The SQL it builds is DELETE FROM "users" WHERE "users"."name" LIKE $1, with the pattern as a parameter.

A bulk delete with no filter is legal and deletes the whole table. The mock check for this page confirms it builds a DELETE with no WHERE clause at all. There is no guardrail in SeaORM that stops it. When a handler deletes by a condition the user supplied, check that the condition is present before calling .exec(), or the empty case becomes a table wipe.

Variations

Deleting from an ActiveModel

When the handler already holds an ActiveModel instead of a Model, Entity::delete deletes from the form.

let result = user::Entity::delete(active).exec(&db).await?;

It builds the same WHERE on the primary key, and it needs the id set or unchanged in the form. A form with the id NotSet fails with DbErr::PrimaryKeyNotSet, the same error the update page reports for a missing key. The two spellings, model.delete(&db) and Entity::delete(active).exec(&db), send the same SQL. The first is shorter when the handler already has a model, which the read-first pattern gives it.

Deleting without loading the row

When the handler only has an id and does not need the 404, a bulk delete with a filter on the id deletes the row in one round trip.

let result = user::Entity::delete_many()
    .filter(user::Column::Id.eq(id))
    .exec(&db)
    .await?;
if result.rows_affected == 0 {
    return Err((StatusCode::NOT_FOUND, "user not found".to_string()));
}

The count does the job the read did. Zero affected means the row was not there. This saves a round trip, and it is the right shape when the handler does not need the row's data. It is the wrong shape when the handler needs to return the deleted row, because a bulk delete never returns one.

How the pieces connect

HTTP DELETE /users/2
    |
    v
Handler reads the row by id
    |  (None -> 404)
    v
Model.delete(&db)
    |
    v
DELETE FROM "users" WHERE "users"."id" = $1
    |
    v
Postgres removes the row, reports 1 affected
    |
    v
Handler answers 204, no body

For a bulk delete the middle is different: no row is read, the filter supplies the WHERE clause, and the answer is the count of removed rows.

Testing

Deletes are easy to test without a database, because the mock database records the SQL and reports a canned row count. 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 affected count the mock should report, runs the delete, and checks the recorded SQL.

use sea_orm::{DatabaseBackend, DbErr, MockDatabase, MockExecResult};

#[tokio::test]
async fn delete_many_reports_affected_rows() -> Result<(), DbErr> {
    let db = MockDatabase::new(DatabaseBackend::Postgres)
        .append_exec_results(vec![MockExecResult {
            last_insert_id: 0,
            rows_affected: 3,
        }])
        .into_connection();
    let result = user::Entity::delete_many()
        .filter(user::Column::Name.like("Test%"))
        .exec(&db)
        .await?;
    assert_eq!(result.rows_affected, 3);
    let log = db.into_transaction_log();
    assert_eq!(log.len(), 1);
    Ok(())
}

append_exec_results queues the outcome of a statement that returns no rows, one MockExecResult per statement, in order. The mock checks in this chapter's scratch project confirm the single-delete SQL shown above, that a bulk delete with a filter reports its count, that deleting a missing row succeeds with zero affected, and that a bulk delete with no filter builds a DELETE with no WHERE clause.

The same deletes were also run against a real Postgres 16 database before it went down for a machine restart. The live run deleted one user by id and reported one row affected, leaving one user in the table.

Common beginner mistakes

Deleting without a filter

// Wrong. With no filter, this deletes every row in the table.
// It compiles, it runs, and it reports a large rows_affected.
let result = user::Entity::delete_many().exec(&db).await?;
// Right. Scope every bulk delete with a filter, and check the
// filter is present when it comes from user input.
let result = user::Entity::delete_many()
    .filter(user::Column::Name.like("Test%"))
    .exec(&db)
    .await?;

There is no guardrail here. SeaORM does not ask "are you sure", and Postgres does not either. A bulk delete is the one place in the chapter where a missing method call is a data-loss bug instead of a compile error.

Expecting a delete to error on a missing row

// Wrong. A bulk delete on a missing id succeeds and reports zero
// affected. There is no error to catch.
let result = user::Entity::delete_many()
    .filter(user::Column::Id.eq(id))
    .exec(&db)
    .await?;
// result.rows_affected is 0, and the handler carries on as if
// the delete worked.
// Right. Read first for the 404, or check the count after a
// bulk delete.
let found = user::Entity::find_by_id(id)
    .one(&db)
    .await?
    .ok_or((StatusCode::NOT_FOUND, "user not found".to_string()))?;
found.delete(&db).await?;

The single delete in the read-first pattern never hits this, because the read already proved the row exists. A delete that skips the read must check rows_affected itself.

Trying to return the deleted row from the delete

// Wrong. delete() returns a DeleteResult, which has only
// rows_affected. There is no model to convert here.
let result = found.delete(&db).await?;
Ok(Json(User::from(result)))
// Right. Copy what the response needs from the model before
// deleting, then delete.
let user = User::from(found);
found.delete(&db).await?;
Ok(Json(user))

A delete returns a count. When the response needs the deleted user's name or email, take them from the model first. After the delete, the row is gone.

Deleting with the id NotSet

// Wrong. The form has no primary key, so the delete has nothing
// to match on.
let active = user::ActiveModel {
    id: NotSet,
    name: Set("Ada".to_owned()),
    email: NotSet,
};
let result = user::Entity::delete(active).exec(&db).await?;
// Right. Build the form from the row, so the id is Unchanged and
// the delete matches on it.
let mut active: user::ActiveModel = found.into();
let result = user::Entity::delete(active).exec(&db).await?;

The error is DbErr::PrimaryKeyNotSet. When you see it on a delete, the form was built by hand instead of from a row, and the id was left out.

Final complete example

Here is the delete handler and a bulk delete 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::{Path, State},
    http::StatusCode,
    routing::delete,
    Json, Router,
};
use sea_orm::{entity::prelude::*, DatabaseConnection};
use seaorm::user;

pub async fn delete_user_handler(
    State(db): State<DatabaseConnection>,
    Path(id): Path<i32>,
) -> Result<StatusCode, (StatusCode, String)> {
    let found = user::Entity::find_by_id(id)
        .one(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "user not found".to_string()))?;
    found
        .delete(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok(StatusCode::NO_CONTENT)
}

pub async fn delete_test_users_handler(
    State(db): State<DatabaseConnection>,
) -> Result<Json<u64>, (StatusCode, String)> {
    let result = user::Entity::delete_many()
        .filter(user::Column::Name.like("Test%"))
        .exec(&db)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok(Json(result.rows_affected))
}

pub fn users_router(db: DatabaseConnection) -> Router {
    Router::new()
        .route("/users/test", delete(delete_test_users_handler))
        .route("/users/:id", delete(delete_user_handler))
        .with_state(db)
}

delete is the Axum function for the HTTP DELETE method, and the route name reads as what it does. The bulk route must come before the /:id route, because Axum matches routes in the order they are added, and /users/test would otherwise be read as an id of test.

Summary

A delete is a select that removes instead of returning, and the same filter vocabulary scopes both. A single delete starts from a model the handler has read, matches on its primary key, and answers with a count of zero or one. A bulk delete starts from delete_many(), takes its scope from .filter(), and answers with however many rows matched. The database never errors on a missing row, so the handler must check for itself, either by reading first for a 404 or by reading rows_affected after a bulk delete. The one asymmetry to remember is that a bulk delete with no filter is legal and removes the whole table, while a single delete cannot make that mistake, because its WHERE clause comes from a row that exists. That is why the read-first pattern is the default for one row, and why a filter is not optional for many.