Skip to main content

TestDb

Struct TestDb 

Source
pub struct TestDb { /* private fields */ }
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 and (crate features model-mysql or model-postgres or model-sqlite) only.

A fresh SQLite in-memory database.

Source

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

Available on crate feature model-postgres and (crate features model-mysql or model-postgres or model-sqlite) 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 and (crate features model-mysql or model-postgres or model-sqlite) 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 and (crate features model-mysql or model-postgres or model-sqlite) 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 and (crate features model-mysql or model-postgres or model-sqlite) 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

Available on crate features model-mysql or model-postgres or model-sqlite only.

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

Source

pub fn backend(&self) -> Backend

Available on crate features model-mysql or model-postgres or model-sqlite only.

Which backend this database is.

Source

pub fn is_transactional(&self) -> bool

Available on crate features model-mysql or model-postgres or model-sqlite only.

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>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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 async fn schema(&self) -> Result<DbSchema, DbError>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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

Source

pub fn primary(&self) -> &DbPool

Available on crate features model-mysql or model-postgres or model-sqlite only.

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

Source

pub fn replica(&self) -> &DbPool

Available on crate features model-mysql or model-postgres or model-sqlite only.

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]

Available on crate features model-mysql or model-postgres or model-sqlite only.

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

Source

pub async fn close(&self)

Available on crate features model-mysql or model-postgres or model-sqlite only.

Close the pool — every pool of a replicated one — waiting for the connections in use to be returned (18.30.0).

Source

pub fn backend(&self) -> Backend

Available on crate features model-mysql or model-postgres or model-sqlite only.

Which backend this pool talks to.

Source

pub async fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, DbError>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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,

Available on crate features model-mysql or model-postgres or model-sqlite only.

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>

Available on crate features model-mysql or model-postgres or model-sqlite only.

Execute a SQL query returning untyped rows (alias for query_rows).

Source

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

Available on crate features model-mysql or model-postgres or model-sqlite only.

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,

Available on crate features model-mysql or model-postgres or model-sqlite only.

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>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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

Source

pub async fn rollback_last(&self, dir: &str) -> Result<Option<String>, DbError>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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 seed_with( &self, dir: &str, seeders: &Seeders, ) -> Result<Vec<String>, DbError>

Available on crate features model-mysql or model-postgres or model-sqlite only.

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