sqlx-cloudflare-d1
A Cloudflare D1 driver for sqlx: a real
sqlx::Databaseover the Workers D1 binding, so code written against sqlx's runtime API runs inside a Rust Worker.
[!NOTE] Pre-1.0. The API may still change between minor versions.
use ;
async
Install
[]
= "0.1"
= { = "0.9", = false, = ["derive"] }
= { = "0.8", = ["d1"] }
| sqlx-cloudflare-d1 | sqlx | worker | Rust |
|---|---|---|---|
| 0.1 | 0.9 | 0.8 | 1.94+ |
The crate runs on wasm32-unknown-unknown, inside a Worker.
Batches
D1 has no interactive transactions, so atomic work is a batch: every statement in one round trip, all applied or none.
// What each statement did.
let results = conn
.execute_batch
.await?;
// Each statement's rows as well, as a stream -- the shape of sqlc's
// `:batchexec`, `:batchone` and `:batchmany` queries.
use TryStreamExt;
use Row;
let names: = conn
.fetch_batch
.map_ok
.try_collect
.await?;
The whole batch runs when the stream is first polled; a failure is the one item it yields, with nothing applied.
Limitations
- No
query!/query_as!macros. sqlx's macros only know its built-in drivers. The runtime API (sqlx::query,query_as,FromRow) works. - No transactions. D1 cannot hold one open across calls, so
begin()fails. Use a batch. - Rows in a batch are keyed by name. D1's
batch()returns rows as objects, so infetch_batchtwo columns with one name collapse to the last. Alias them apart inside a batch. - No
sqlx::Pool. Nothing to pool: build a connection per request from the binding. - Integers are limited to ±(2^53 − 1). D1 passes values as JavaScript
numbers, so a wider
i64is refused rather than silently rounded. Note that sqlx'sQueryBuilder::push_bindpanics on a refused value instead of returning the error. - No
sqlx::migrate!. Apply migrations withwrangler d1 migrations. - No derived TEXT enums.
#[derive(sqlx::Type)]works for#[sqlx(transparent)]newtypes and#[repr(i32)]enums, but sqlx only generates string-backed enums for its built-in drivers. - No statement logging.
log_statementsis accepted and ignored. - Results are not streamed. D1 returns a whole result set at once.