Skip to main content

DbPool

Enum DbPool 

Source
pub enum DbPool {
    Sqlite(Pool<Sqlite>),
    Postgres(Pool<Postgres>),
    MySql(Pool<MySql>),
    Replicated(Arc<Replicas>),
}
Available on crate features 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>)

Available on crate feature model-sqlite only.
§

Postgres(Pool<Postgres>)

Available on crate feature model-postgres only.
§

MySql(Pool<MySql>)

Available on crate feature 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

Source

pub async fn schema(&self) -> Result<DbSchema, DbError>

The connected schema’s tables (18.30.0), read from the primary: see db_schema.

Source§

impl DbPool

Source

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).

Source

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.

Source

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.

Source

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 replica
Source

pub fn primary(&self) -> &DbPool

The pool writes go to: the primary of a replicated pool, else this pool (18.30.0).

Source

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).

Source

pub fn replicas(&self) -> &[DbPool]

A replicated pool’s replicas; empty for any other (18.30.0).

Source

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).

Source

pub async fn memory() -> Result<DbPool, DbError>

Available on crate feature 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());
Source

pub fn backend(&self) -> Backend

Which backend this pool talks to.

Source

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.

Source

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.

Source

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.

Source

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).

Source

pub async fn begin(&self) -> Result<DbTransaction, DbError>

Begin a transaction. Call DbTransaction::commit to commit or let it drop to automatically roll back.

Source

pub async fn transaction<F, T, Fut>(&self, f: F) -> Result<T, DbError>
where F: FnOnce(DbTransaction) -> Fut + Send, Fut: Future<Output = Result<T, DbError>> + Send, T: Send,

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);
Source

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.

Source

pub async fn migration_status( &self, dir: &str, ) -> Result<Vec<MigrationStatus>, DbError>

Return the status (applied / pending) for each SQL file in dir.

Source

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.

Source

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.

Source

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.

Source

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.

Source§

impl DbPool

Source

pub async fn seed_with( &self, dir: &str, seeders: &Seeders, ) -> Result<Vec<String>, DbError>

seed the *.sql files in dir, then run seeders (18.30.0); answers the files and the seeders’ names, in the order they ran. With seeders, a missing dir means no SQL seeds rather than an error.

Trait Implementations§

Source§

impl Clone for DbPool

Source§

fn clone(&self) -> DbPool

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DbPool

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ServiceExt for T

Source§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Available on crate feature map-response-body only.
Apply a transformation to the response body. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using gRPC headers. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more