expression

SQLx: isolate database access in a repository

A repository exposes domain-focused operations and hides SQL details from callers. The small concrete adapter uses a borrowed PgPool and returns Option for absence while preserving database errors. The query uses a synthetic dataset instead of a persistent table. Real application authorization and transaction boundaries still belong in an appropriate service layer. Requires an explicitly authorized disposable local PostgreSQL lab with verified TLS; see fixture README. Expected stdout (not executed): 2: Book missing: true Common mistake: Converting all database errors into None, or assuming a repository automatically enforces authorization.

Formal Syntax & Structure

rust syntaxrust
async fn find(&self, id: i32) -> Result<Option<Item>, sqlx::Error>

Working Example

Example Snippetrust
async fn lab_pool() -> Result<sqlx::PgPool, Box<dyn std::error::Error>> {    use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgSslMode};    use std::time::Duration;    if std::env::var("BM_SQLX_LAB_OPT_IN").as_deref() != Ok("yes") {        return Err("disposable PostgreSQL lab required".into());    }    // Reject ambient PostgreSQL settings to keep the target explicit.    if std::env::vars_os().any(|(key, _)| key.to_string_lossy().to_ascii_uppercase().starts_with("PG")) {        return Err("remove ambient PG* environment settings".into());    }    let password = std::env::var("BM_SQLX_LAB_PASSWORD")?;    let ca = std::env::var("BM_SQLX_LAB_CA")?;    let options = PgConnectOptions::new_without_pgpass()        .host("127.0.0.1").port(55432)        .username("bm_learner").database("bm_sqlx_v87_lab")        .password(&password).ssl_mode(PgSslMode::VerifyFull)        .ssl_root_cert(ca);    let pool = PgPoolOptions::new().max_connections(2)        .acquire_timeout(Duration::from_secs(3))        .connect_with(options).await?;    Ok(pool)}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    #[derive(sqlx::FromRow)]    struct Item { id: i32, name: String }    struct ItemRepository<'a> { pool: &'a sqlx::PgPool }    impl ItemRepository<'_> {        async fn find(&self, id: i32) -> Result<Option<Item>, sqlx::Error> {            sqlx::query_as("SELECT id, name FROM (VALUES (1, 'Pen'), (2, 'Book')) AS t(id, name) WHERE id = $1")                .bind(id).fetch_optional(self.pool).await        }    }    let pool = lab_pool().await?;    let repo = ItemRepository { pool: &pool };    let item = repo.find(2).await?.ok_or("expected item")?;    println!("{}: {}", item.id, item.name);    println!("missing: {}", repo.find(9).await?.is_none());    pool.close().await;    Ok(())}
Rust Reference