Skip to main content

DbPool

Enum DbPool 

Source
pub enum DbPool {
    Sqlite(Pool<Sqlite>),
    Postgres(Pool<Postgres>),
    MySql(Pool<MySql>),
}
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.

Implementations§

Source§

impl DbPool

Source

pub async fn new(config: DbConfig) -> Result<Self, 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<Self, 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<Self, DbError>

Create a pool using DbConfig::from_env and DbTls::from_env.

Source

pub async fn memory() -> Result<Self, 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.

Source

pub async fn query<T: Model>( &self, sql: &str, params: &[Value], ) -> Result<Vec<T>, DbError>

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.

Trait Implementations§

Source§

impl Clone for DbPool

Source§

fn clone(&self) -> Self

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

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