pub enum DbPool {
Sqlite(Pool<Sqlite>),
Postgres(Pool<Postgres>),
MySql(Pool<MySql>),
}model-mysql or model-postgres or model-sqlite only.Expand description
An async connection pool backed by sqlx.
Cheap to clone — the inner pool is reference-counted. Which variant a
DbPool is depends on the Backend it was created with; see the module
docs for running more than one backend in the same binary.
Variants§
Sqlite(Pool<Sqlite>)
model-sqlite only.Postgres(Pool<Postgres>)
model-postgres only.MySql(Pool<MySql>)
model-mysql only.Implementations§
Source§impl DbPool
impl DbPool
Sourcepub async fn new(config: DbConfig) -> Result<DbPool, DbError>
pub async fn new(config: DbConfig) -> Result<DbPool, DbError>
Create a new pool for config.backend, with the given configuration
and the default TLS (DbTls::default: TLS when the server offers
it, certificate not checked).
Sourcepub async fn new_with_tls(
config: DbConfig,
tls: DbTls,
) -> Result<DbPool, DbError>
pub async fn new_with_tls( config: DbConfig, tls: DbTls, ) -> Result<DbPool, DbError>
As DbPool::new, with tls for PostgreSQL and MySQL (SQLite
ignores it). User and password are passed as they are, not through a
URL, so any characters work.
Sourcepub async fn from_env() -> Result<DbPool, DbError>
pub async fn from_env() -> Result<DbPool, DbError>
Create a pool using DbConfig::from_env and DbTls::from_env.
Sourcepub async fn memory() -> Result<DbPool, DbError>
Available on crate feature model-sqlite only.
pub async fn memory() -> Result<DbPool, DbError>
model-sqlite only.Create a pool backed by a SQLite in-memory database.
All connections in the pool share the same in-memory database (max_connections = 1). Each call returns an independent, isolated database — ideal for tests.
use rust_web_server::model::{DbPool, Value};
let pool = DbPool::memory().await?;
pool.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)", &[]).await?;
pool.execute("INSERT INTO t (v) VALUES (?)", &[Value::Text("hello".into())]).await?;
let rows = pool.query_rows("SELECT * FROM t", &[]).await?;
assert_eq!(1, rows.len());Sourcepub async fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, DbError>
pub async fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, DbError>
Execute a SQL statement (INSERT / UPDATE / DELETE / DDL).
Returns the number of rows affected.
Sourcepub async fn query_rows(
&self,
sql: &str,
params: &[Value],
) -> Result<Vec<ModelRow>, DbError>
pub async fn query_rows( &self, sql: &str, params: &[Value], ) -> Result<Vec<ModelRow>, DbError>
Execute a SQL query and return untyped rows.
Sourcepub async fn query<T>(
&self,
sql: &str,
params: &[Value],
) -> Result<Vec<T>, DbError>where
T: Model,
pub async fn query<T>(
&self,
sql: &str,
params: &[Value],
) -> Result<Vec<T>, DbError>where
T: Model,
Execute a SQL query and deserialise results into T: Model.
Sourcepub async fn query_raw(
&self,
sql: &str,
params: &[Value],
) -> Result<Vec<ModelRow>, DbError>
pub async fn query_raw( &self, sql: &str, params: &[Value], ) -> Result<Vec<ModelRow>, DbError>
Execute a SQL query returning untyped rows (alias for query_rows).
Sourcepub async fn begin(&self) -> Result<DbTransaction, DbError>
pub async fn begin(&self) -> Result<DbTransaction, DbError>
Begin a transaction. Call DbTransaction::commit to commit or let it
drop to automatically roll back.
Sourcepub async fn transaction<F, T, Fut>(&self, f: F) -> Result<T, DbError>
pub async fn transaction<F, T, Fut>(&self, f: F) -> Result<T, DbError>
Run a closure in a transaction.
The closure owns the transaction: call tx.commit() before returning
Ok. A transaction that isn’t committed — the closure returns Err,
or Ok without committing — is dropped, which rolls it back.
use rust_web_server::model::{DbPool, Value};
let pool = DbPool::memory().await?;
let result = pool.transaction(|mut tx| async move {
tx.execute("INSERT INTO t (v) VALUES (?)", &[Value::Text("hi".into())]).await?;
tx.commit().await?;
Ok(42i32)
}).await?;
assert_eq!(42, result);Sourcepub async fn migrate(&self, dir: &str) -> Result<(), DbError>
pub async fn migrate(&self, dir: &str) -> Result<(), DbError>
Run pending migrations from SQL files in dir.
Files are applied in lexicographic order. Already-applied versions are
tracked in a _schema_migrations table (created if absent). Idempotent.
Sourcepub async fn migration_status(
&self,
dir: &str,
) -> Result<Vec<MigrationStatus>, DbError>
pub async fn migration_status( &self, dir: &str, ) -> Result<Vec<MigrationStatus>, DbError>
Return the status (applied / pending) for each SQL file in dir.
Sourcepub async fn rollback_last(&self, dir: &str) -> Result<Option<String>, DbError>
pub async fn rollback_last(&self, dir: &str) -> Result<Option<String>, DbError>
Roll back the most recently applied migration in dir.
Requires a companion <version-stem>.down.sql file next to the up
migration it undoes (e.g. 0001_x.sql → 0001_x.down.sql); returns
Err if that file is missing. Returns Ok(None) if nothing is
currently applied.
Sourcepub async fn rollback(
&self,
dir: &str,
n: usize,
) -> Result<Vec<String>, DbError>
pub async fn rollback( &self, dir: &str, n: usize, ) -> Result<Vec<String>, DbError>
Roll back the last n applied migrations, most recently applied
first. Returns the versions actually rolled back — fewer than n if
fewer than n migrations were applied. Stops at the first missing
down file or SQL error; migrations already rolled back in earlier
iterations stay rolled back.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for DbPool
impl !UnwindSafe for DbPool
impl Freeze for DbPool
impl Send for DbPool
impl Sync for DbPool
impl Unpin for DbPool
impl UnsafeUnpin for DbPool
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<T> ServiceExt for T
impl<T> ServiceExt for T
Source§fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>where
Self: Sized,
fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>where
Self: Sized,
map-response-body only.Source§fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
trace only.Source§fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
trace only.