FAQ - Help and questions

How do I load one row into a struct with sqlx and answer 404 when it is missing?

#sqlx#axum#query-as#databasepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Derive FromRow on the struct, call sqlx::query_as with .bind() for each placeholder and finish with fetch_optional. It returns Ok(None) when no row matches, which you map to 404, while a real database failure stays an Err you map to 500. fetch_one would turn a missing row into an error.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, sqlx 0.8.6 (SQLite), Windows 11; run in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Three results are possible and each needs its own status: a row, no row, and a database error. fetch_optional keeps the first two apart from the third:

src/main.rsrust
use axum::{
    body::{to_bytes, Body},
    extract::{Path, State},
    http::{Request, StatusCode},
    routing::get,
    Json, Router,
};
use serde::Serialize;
use sqlx::{FromRow, SqlitePool};
use tower::ServiceExt;

#[derive(Serialize, FromRow)]
struct Todo { id: i64, title: String, done: bool }

async fn show(State(db): State<SqlitePool>, Path(id): Path<i64>) -> Result<Json<Todo>, StatusCode> {
    sqlx::query_as::<_, Todo>("SELECT id, title, done FROM todos WHERE id = ?")
        .bind(id)
        .fetch_optional(&db)                                  // Ok(None) when no row matches
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?      // a real database failure
        .map(Json)
        .ok_or(StatusCode::NOT_FOUND)                         // no row: 404
}

#[tokio::main]
async fn main() {
    let db = SqlitePool::connect("sqlite::memory:").await.unwrap();
    sqlx::migrate!("./migrations").run(&db).await.unwrap();
    sqlx::query("INSERT INTO todos (id, title) VALUES (1, 'write docs')").execute(&db).await.unwrap();

    let app = Router::new().route("/todos/{id}", get(show)).with_state(db);
    for uri in ["/todos/1", "/todos/2"] {
        let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
        let status = res.status().as_u16();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{uri} -> {status} {}", String::from_utf8_lossy(&body));
    }
}
text
/todos/1 -> 200 {"id":1,"title":"write docs","done":false}
/todos/2 -> 404 
  • #[derive(FromRow)] maps columns to fields by name.
  • .bind(id) fills the ? placeholder; the value is never pasted into the SQL text.
  • .map(Json) runs only when a row was found; .ok_or(StatusCode::NOT_FOUND) turns None into 404.
Cargo.tomltoml
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio", "sqlite", "migrate", "macros"] }

Common mistakes#

  • Using fetch_one for a lookup by id. A missing row is then an error (RowNotFound) that is easy to turn into a 500 by mistake.
  • Mapping every database error to 404 to "keep it simple": a broken connection would then look like missing data.
  • Selecting * into a struct. Name the columns, so a new column cannot break the mapping.

How do I get many rows?#

fetch_all returns a Vec; for large results fetch gives a stream. Add LIMIT (see the thread on pagination).

Why ? placeholders here and $1 in other tutorials?#

The placeholder syntax belongs to the database: SQLite uses ?, PostgreSQL uses $1. This thread ran SQLite only.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet