Skip to main content

Crate bsql

Crate bsql 

Source
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(&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

MethodReturnsUse
.fetch(&pool).awaitVec<Row>SELECT queries
.run(&pool).awaitu64INSERT, 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.
Pool
A PostgreSQL connection pool.
PoolBuilder
Builder for configuring a connection pool.
PoolStatus
Snapshot of pool utilization.
QueryStream
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§

BsqlError
The error type for all bsql operations.
IsolationLevel
Transaction isolation levels supported by PostgreSQL.

Type Aliases§

BsqlResult
Convenience alias used throughout bsql.

Attribute Macros§

pg_enum
Derive PostgreSQL enum <-> Rust enum mapping with FromSql and ToSql.
sort
Define a sort enum for compile-time verified dynamic ORDER BY clauses.
test
Attribute macro for database integration tests with schema isolation.