Expand description
§zirv-db-sqlx
A small, convenient wrapper around sqlx that standardises three things across a service:
- Global connection pool managed in a process-wide
OnceLock, initialized once withinit_db_pool!and read anywhere withget_db_pool!. - Tunable pool settings read from the
database.*configuration namespace viazirv-config(seedb::PoolSettings). - Transaction helpers (
start_transaction!,commit_transaction!,rollback_transaction!) that remove the usual boilerplate.
The crate also exposes close_db_pool for graceful shutdown.
§Choosing a database backend
Enable exactly one of the mysql (default), postgres, or sqlite features,
together with exactly one runtime/TLS feature (runtime-tokio-native-tls,
the default, or runtime-tokio-rustls). For a non-default backend, disable
default features:
# PostgreSQL with rustls
zirv-db-sqlx = { version = "0.3", default-features = false, features = ["postgres", "runtime-tokio-rustls"] }§Example
use zirv_config::register_config;
use zirv_db_sqlx::{init_db_pool, get_db_pool, close_db_pool};
#[derive(serde::Serialize)]
struct DatabaseConfig {
url: String,
max_connections: u32,
}
register_config!("database", DatabaseConfig {
url: "mysql://user:password@localhost/db".to_string(),
max_connections: 10,
});
init_db_pool!();
let pool = get_db_pool!();
// ... use `pool` with sqlx queries ...
close_db_pool().await; // graceful shutdownRe-exports§
pub use db::Db;pub use db::DbPool;pub use db::PoolSettings;pub use db::close_db_pool;
Modules§
- db
- Global connection-pool management for the compile-time selected database backend.
Macros§
- commit_
transaction - Commits an active transaction, logging and returning the error on failure.
- get_
db_ pool - Retrieves a reference to the global database pool.
- init_
db_ pool - Initializes the global database pool.
- rollback_
transaction - Rolls back an active transaction, logging and returning the error on failure.
- start_
transaction - Begins a new transaction on the global pool.