D1 databases are in alpha and require the d1 feature flag in your Cargo.toml.
To use D1, access the database via env.d1("binding_name")?. You can then prepare statements, bind parameters, and execute queries (e.g., .first::<T>(None).await?) to retrieve data mapped to Rust structs.
# Cargo.toml
worker = { version = "x.y.z", features = ["d1"] }
use worker::*;
#[derive(Deserialize)]
struct Thing {
thing_id: String,
desc: String,
num: u32,
}
#[event(fetch, respond_with_errors)]
pub async fn main(request: Request, env: Env, _ctx: Context) -> Result<Response> {
Router::new()
.get_async("/:id", |_, ctx| async move {
let id = ctx.param("id").unwrap()?;
d1 = ctx.env.d1("things-db")?;
let statement = d1.prepare("SELECT * FROM things WHERE thing_id = ?1");
let query = statement.bind(&[id])?;
let result = query.first::<Thing>(None).await?;
match result {
Some(thing) => Response::from_json(&thing),
None => Response::error("Not found", 404),
}
})
.run(request, env)
.await
}