Expand description
§bsql — Safe SQL for Rust
If it compiles, the SQL is correct.
bsql validates every SQL query against a real database at compile time.
Async by default — all user-facing methods are async fn.
§Quick Start
[dependencies]
bsql = "0.20"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }ⓘ
use bsql::Pool;
#[tokio::main]
async fn main() -> Result<(), bsql::BsqlError> {
let pool = Pool::connect("postgres://user:pass@localhost/mydb").await?;
let id = 1i32;
let users = bsql::query!(
"SELECT id, login, active FROM users WHERE id = $id: i32"
).fetch_all(&pool).await?;
let user = &users[0];
// user.id: i32, user.login: String, user.active: bool
println!("{}: active={}", user.login, user.active);
Ok(())
}§Two methods — that’s it
| Method | Returns | Use |
|---|---|---|
.fetch_all(&pool).await | Vec<Row> | SELECT queries |
.execute(&pool).await | u64 | INSERT, UPDATE, DELETE |
Also: fetch_one, fetch_optional, fetch_stream, for_each, defer (for transactions).
§Escape hatch
For rare cases requiring dynamic SQL (dynamic table names, pivots, DDL):
ⓘ
let rows = pool.raw_query("SELECT * FROM pg_tables LIMIT 5").await?;
pool.raw_execute("CREATE INDEX CONCURRENTLY idx ON users (email)").await?;raw_query / raw_execute bypass compile-time validation entirely.
Use query! for everything else.
Modules§
- error
- Error types for bsql.
Macros§
- query
- Validate a SQL query against PostgreSQL at compile time and generate typed Rust code for executing it.
- query_
as - Map query results into a user-defined struct at compile time.
Structs§
- Listener
- A dedicated LISTEN/NOTIFY connection to PostgreSQL.
- Notification
- A notification received from PostgreSQL via LISTEN/NOTIFY.
- PgPool
- A PostgreSQL connection pool.
- Pool
Builder - Builder for configuring a connection pool.
- Pool
Status - Snapshot of pool utilization.
- Query
Stream - A stream of rows backed by true PG-level chunked fetching.
- RawRow
- A row of text values from a raw (unvalidated) SQL query.
- Transaction
- A database transaction.
Enums§
- Bsql
Error - The error type for all bsql operations.
- Isolation
Level - Transaction isolation levels supported by PostgreSQL.
Type Aliases§
- Bsql
Result - Convenience alias used throughout bsql.
- Pool
- Backward-compatible type alias. Use
PgPoolfor new code.