FAQ - Help and questions

How do I connect to a database with sqlx and share the pool in axum?

#sqlx#axum#database#connection-poolpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Create one SqlitePool at start-up with PoolOptions (maximum connections and an acquire timeout), put it in the application state, and pass &pool to every query. The pool is a cheap handle to shared connections, so clone it freely. Create the pool once, not per request.

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#

Opening a database connection is slow, so web programs keep a pool of open connections and lend one to each query. In sqlx the pool is cloneable and safe to share, so it goes straight into the axum state.

src/main.rsrust
use axum::{body::{to_bytes, Body}, extract::State, http::{Request, StatusCode}, routing::get, Router};
use sqlx::{sqlite::{SqliteConnectOptions, SqlitePoolOptions}, SqlitePool};
use std::time::Duration;
use tower::ServiceExt;

#[derive(Clone)]
struct AppState { db: SqlitePool } // a pool is cheap to clone: it is a handle to shared connections

async fn count(State(s): State<AppState>) -> Result<String, StatusCode> {
    let n: i64 = sqlx::query_scalar("SELECT count(*) FROM notes")
        .fetch_one(&s.db)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(format!("{n} notes"))
}

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let path = std::env::temp_dir().join("rs-sqlx-demo.db");
    let _ = std::fs::remove_file(&path);
    let options = SqliteConnectOptions::new().filename(&path).create_if_missing(true);
    let pool = SqlitePoolOptions::new()
        .max_connections(5)
        .acquire_timeout(Duration::from_secs(3)) // fail with an error instead of waiting forever
        .connect_with(options)
        .await?;

    sqlx::query("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)").execute(&pool).await?;
    sqlx::query("INSERT INTO notes (body) VALUES (?), (?)").bind("first").bind("second").execute(&pool).await?;

    let app = Router::new().route("/count", get(count)).with_state(AppState { db: pool });
    let res = app.oneshot(Request::get("/count").body(Body::empty()).unwrap()).await.unwrap();
    let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
    println!("{}", String::from_utf8_lossy(&body));
    Ok(())
}
text
2 notes
  • max_connections(5) caps how many connections exist at once. When all are in use, the next query waits.
  • acquire_timeout turns an endless wait into an error after three seconds, which your handler can turn into a 503 or 500.
  • .fetch_one(&s.db) passes the pool as the executor; sqlx borrows a connection for that one query and returns it.
  • SQLite is used because it needs no server. Other databases use their own feature (postgres, mysql) and pool type, with the same style of code; this thread ran only SQLite.
Cargo.tomltoml
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio", "sqlite"] }

Common mistakes#

  • Calling SqlitePool::connect inside a handler. Every request would then create its own pool.
  • Setting max_connections higher than the database accepts. Check your database's connection limit.
  • Building SQL with format! and user input. Use .bind(value) as in the example: the value travels separately from the SQL text.

What happens to a request when the pool is empty?#

It waits up to the acquire timeout, then the query returns an error (PoolTimedOut), which is your cue to log it and answer with an error status.

Does a pool help with SQLite in a file?#

It lets several connections read at once; writes to one SQLite file are still serialized by the database. This thread did not measure either.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet