SQLx-D1 realizes "SQLx for Cloudflare D1" with compile-time SQL verification in Rust Cloudflare development !
Background
Miniflare's local D1 emulator is, essentially, just a .sqlite
file.
This fact has been brought a lot of Rustaceans trying sqlx
with sqlite
feature for D1, but it's impossible because:
sqlx-sqlite
contains a native dependency of SQLite driver.- actual D1 itself doesn't expose raw database interface.
SQLx-D1 works around them by loading sqlx-sqlite
only in macro context and just providing a conversion layer between D1 and SQLx in library context.
Features
- SQLx interface for Cloudflare D1
- Batteries included,
sqlx
is not needed in dependencies - Compile-time SQL verification
- by
sqlx-sqlite
and miniflare's local D1 emulator - by query caches in
.sqlx
directory ( offline mode )
- by
- No environment variable or
.env
file is needed- D1 emulator's location is fixed to
.wrangler/state/v3/d1/miniflare-D1DatabaseObject
- falling back to offline mode when it doesn't exist and
.sqlx
directory exists
- D1 emulator's location is fixed to
Unsupported features
- Transaction
- Let's wait for Cloudflare's side to support transation on D1 !
- Connection pool (
sqlx::Pool
internally requires Rust async runtime (tokio / asycn-std) and time implemetation of WASM runtime which is not done on Cloudflare Workers )- alternatively,
&sqlx_d1::D1Connection
implementsExecutor
, not only&mut
one.
- alternatively,
- derive
Type
,Encode
,Decode
- maybe added if requested
- workaround if needed: add
sqlx
to dependencies and use its ones
Example
# Cargo.toml
[]
= { = "0.1", = ["macros"] }
= { = "0.5", = ["d1"] }
= { = "1.0", = ["derive"] }
# wrangler.toml
[[]]
= "DB"
= "<DATABASE_NAME>"
= "<DATABASE_ID>"
-- migrations/0001_schema.sql
(
id INTEGER NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
);
// src/lib.rs
async
LICENSE
SQLx-D1 is licensed under MIT LICENSE ( LICENSE or https://opensource.org/licenses/MIT ) .