Skip to main content

TestDb

Struct TestDb 

Source
pub struct TestDb { /* private fields */ }
Available on crate features model-mysql or model-postgres or model-sqlite only.
Expand description

A database for one test; see the module docs.

Implementations§

Source§

impl TestDb

Source

pub fn sqlite() -> TestDbBuilder

Available on crate feature model-sqlite only.

A fresh SQLite in-memory database.

Source

pub fn postgres(url: &str) -> TestDbBuilder

Available on crate feature model-postgres only.

The PostgreSQL database at url (postgres://user:password@host/db, sqlx’s URL syntax), each test inside a transaction that’s rolled back.

Source

pub fn mysql(url: &str) -> TestDbBuilder

Available on crate feature model-mysql only.

The MySQL database at url (mysql://user:password@host/db), each test inside a transaction that’s rolled back.

Source

pub fn postgres_from_env() -> Option<TestDbBuilder>

Available on crate feature model-postgres only.

TestDb::postgres with the URL in RWS_TEST_POSTGRES_URL; None (after printing that the test is skipped) when it isn’t set, so a test can return early on a machine without the server:

use rust_web_server::test_client::TestDb;

let Some(db) = TestDb::postgres_from_env() else { return Ok(()) };
let db = db.migrations("migrations").await?;
Source

pub fn mysql_from_env() -> Option<TestDbBuilder>

Available on crate feature model-mysql only.

TestDb::mysql with the URL in RWS_TEST_MYSQL_URL; None (after printing that the test is skipped) when it isn’t set.

Source

pub fn pool(&self) -> DbPool

A clone of the pool (cheap: same connections, same database), for the app’s state.

Source

pub fn backend(&self) -> Backend

Which backend this database is.

Source

pub fn is_transactional(&self) -> bool

true for PostgreSQL / MySQL, whose writes are rolled back; false for SQLite, whose database is dropped instead.

Source

pub async fn rollback(self) -> Result<(), DbError>

End the test now: roll the transaction back (PostgreSQL, MySQL) and close the pool. Dropping the TestDb does the same without waiting for it; this reports errors.

Methods from Deref<Target = DbPool>§

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 Deref for TestDb

Source§

type Target = DbPool

The resulting type after dereferencing.
Source§

fn deref(&self) -> &DbPool

Dereferences the value.
Source§

impl Drop for TestDb

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. 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> 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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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