pub enum DbPool {
Sqlite(Pool<Sqlite>),
Postgres(Pool<Postgres>),
MySql(Pool<MySql>),
Replicated(Arc<Replicas>),
}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.Replicated(Arc<Replicas>)
A primary and its read replicas (18.30.0): made by
DbPool::with_replicas or DbPool::from_env with
RWS_DB_REPLICA_URLS. Reads (query_rows,
query, the query builder’s fetch_* / count,
the repository’s find_* / count) go to a replica, round robin;
writes, transactions, migrations and seeds go to the primary. Code
that matches on DbPool’s variants needs an arm for this one —
DbPool::close closes any.
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.
With RWS_DB_REPLICA_URLS set (18.30.0) — comma-separated database
URLs as DbPool::connect takes them, each with
RWS_DB_POOL_SIZE connections at most — the pool is
replicated: reads go to those replicas,
writes to the database the other RWS_DB_* variables name.
Sourcepub fn with_replicas(
primary: DbPool,
replicas: Vec<DbPool>,
) -> Result<DbPool, DbError>
pub fn with_replicas( primary: DbPool, replicas: Vec<DbPool>, ) -> Result<DbPool, DbError>
A pool that sends reads to replicas (round robin) and everything
else to primary (18.30.0). Reads are query_rows,
query, query_raw — so
QueryBuilder::fetch_all / fetch_one / count / paginate, the
repository’s find_by_id / find_all / count / exists_by_id
and relation loads. execute,
begin / transaction (reads
inside a transaction too), migrations, seeds, schema
and save (which reads the saved row back) go to the primary.
A replica lags behind its primary: a read right after a write may not
see it. Read from primary when it must
(User::query(pool.primary())). With no replicas every statement
goes to the primary. An error when a replica’s backend differs from
the primary’s; a replicated primary contributes its primary and
replicas.
use rust_web_server::model::{DbPool, Value};
let pool = DbPool::with_replicas(
DbPool::connect("postgres://app:secret@db-primary/app").await?,
vec![DbPool::connect("postgres://app:secret@db-replica-1/app").await?],
)?;
pool.execute("UPDATE users SET active = false WHERE id = $1", &[Value::Int(7)]).await?; // the primary
let rows = pool.query_rows("SELECT * FROM users", &[]).await?; // a replicaSourcepub fn primary(&self) -> &DbPool
pub fn primary(&self) -> &DbPool
The pool writes go to: the primary of a replicated pool, else this pool (18.30.0).
Sourcepub fn replica(&self) -> &DbPool
pub fn replica(&self) -> &DbPool
The pool the next read goes to: a replicated pool’s replicas in turn (its primary when it has none), else this pool (18.30.0).
Sourcepub fn replicas(&self) -> &[DbPool]
pub fn replicas(&self) -> &[DbPool]
A replicated pool’s replicas; empty for any other (18.30.0).
Sourcepub async fn close(&self)
pub async fn close(&self)
Close the pool — every pool of a replicated one — waiting for the connections in use to be returned (18.30.0).
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 — on a replica when the pool has them.
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.
Sourcepub async fn seed(&self, dir: &str) -> Result<Vec<String>, DbError>
pub async fn seed(&self, dir: &str) -> Result<Vec<String>, DbError>
Run the seed files in dir (18.30.0): every *.sql file, in
lexicographic order, each in its own transaction (statements split
at ;, as migrations). Unlike migrations nothing records that a
seed ran — it runs again every time, so write seeds that can (INSERT … ON CONFLICT DO NOTHING on PostgreSQL and SQLite, INSERT IGNORE
on MySQL). Answers the files run; stops at the first that fails,
whose statements are rolled back.
Sourcepub async fn connect(url: &str) -> Result<DbPool, DbError>
pub async fn connect(url: &str) -> Result<DbPool, DbError>
A pool for a database URL (18.30.0): sqlite:<path> (or
sqlite::memory:), postgres://user:password@host:port/db (also
postgresql://), mysql://user:password@host:port/db (also
mariadb://) — sqlx’s syntax, query parameters included (sslmode,
ssl-mode, …). The backend’s model-* feature must be compiled in.
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.