Skip to main content

Db

Struct Db 

Source
pub struct Db { /* private fields */ }
Expand description

Handle to a database: a pool, or an open transaction.

Implementations§

Source§

impl Db

Source

pub async fn transaction<F, Fut, T, E>(&self, f: F) -> Result<T, E>
where F: FnOnce(Db) -> Fut, Fut: Future<Output = Result<T, E>>, E: From<OrmError>,

Run f in a transaction, or a savepoint inside a transaction.

Cancelling a closure, child scope or statement makes the transaction unusable. An outer success then fails and rolls back. Concurrent statements and sibling scopes are rejected; recursive nesting through the child is supported. Use the child handle while its scope is active. Escaped handles cannot execute after their scope finishes. Cancellation during COMMIT can leave the server outcome unknown; callers must not retry blindly.

Args: f: Closure receiving the scoped transaction handle.

Returns: The closure result after commit or confirmed savepoint release.

§Errors

Closure, backend, capability, busy-scope or aborted-transaction errors.

Source

pub async fn transaction_with<F, Fut, T, E>( &self, isolation: IsolationLevel, f: F, ) -> Result<T, E>
where F: FnOnce(Db) -> Fut, Fut: Future<Output = Result<T, E>>, E: From<OrmError>,

Run a scoped transaction at an explicit isolation level.

Args: isolation: A level supported by the backend; disallowed in nesting. f: Closure receiving the scoped transaction handle.

Returns: The closure result after successful commit.

§Errors

As transaction, plus unsupported isolation.

Source

pub async fn schema_change<F, Fut, T, E>( &self, transactional: bool, f: F, ) -> Result<T, E>
where F: FnOnce(Db) -> Fut, Fut: Future<Output = Result<T, E>>, E: From<OrmError>,

Run f on a dedicated schema connection, optionally transactional.

SQLite disables foreign keys before BEGIN and restores them afterwards. A cancelled nested scope makes the connection unusable; it cannot be committed through an escaped handle.

Args: transactional: Whether to wrap schema work in a transaction. f: Closure receiving the dedicated connection handle.

Returns: The closure result after the backend finishes schema work.

§Errors

Closure/backend errors; SQLite rejects an already-scoped connection.

Source

pub fn on_commit(&self, hook: impl FnOnce() + Send + 'static)

Register work after the outermost transaction successfully commits.

Hooks of failed or abandoned scopes are discarded. Registration on closed, aborted or temporarily inactive handles is discarded as well. Outside a transaction the callback runs immediately.

Args: hook: Callback invoked after commit.

Returns: None.

Source§

impl Db

Source

pub fn new(backend: impl Backend) -> Self

Wrap a backend (connection pool).

Source

pub fn from_arc(backend: Arc<dyn Backend>) -> Self

Wrap a shared backend.

Source

pub fn with_signals(self, signals: Signals) -> Self

Attach the Signals registry model operations dispatch to.

The registry is shared by clones of this handle and by the transaction handles opened from it.

Source

pub fn signals(&self) -> &Signals

The signal registry of this handle.

Source

pub fn same_database(&self, other: &Db) -> bool

Whether self and other talk to the same database: two handles of one pool, or a transaction and the pool it was opened on.

Source

pub fn capabilities(&self) -> BackendCapabilities

Declared capabilities of the underlying backend.

Source

pub fn read_parameter_count( &self, plan: &QueryPlan, ) -> Result<Option<usize>, OrmError>

Count read-plan binds through the backend compiler without I/O.

Args: plan: Complete target read plan, including existing filters.

Returns: Exact count when supported; None for non-reporting backends.

§Errors

Foreign database origin, invalid plan or unsupported capability.

Source

pub fn in_transaction(&self) -> bool

Whether this handle runs inside a transaction.

Source

pub fn is_scoped(&self) -> bool

Whether this handle owns a connection or transaction scope.

Returns: True for scoped handles; false for a pool handle.

Source

pub async fn fetch(&self, plan: &QueryPlan) -> Result<QueryResult, OrmError>

Execute a read plan.

§Errors

Capability, backend or decode errors.

Source

pub async fn execute(&self, plan: &WritePlan) -> Result<ExecResult, OrmError>

Execute a write plan.

§Errors

Capability or backend errors.

Source

pub async fn raw_sql( &self, sql: &str, params: Vec<Value>, ) -> Result<QueryResult, OrmError>

Raw SQL returning rows (db.raw_sql("SELECT .. WHERE id = ?", params![id])).

Placeholders follow the backend (? on SQLite, $1 on PostgreSQL). Parameters are always bound; never format untrusted input into sql.

§Errors

Backend errors.

Source

pub async fn raw_execute( &self, sql: &str, params: Vec<Value>, ) -> Result<u64, OrmError>

Raw SQL returning the affected-row count. Parameters are bound.

§Errors

Backend errors.

Source

pub async fn execute_script(&self, sql: &str) -> Result<(), OrmError>

Run a parameterless multi-statement script (DDL).

§Errors

Backend errors.

Source§

impl Db

Source

pub fn objects<M: Model>(&self) -> QuerySet<M>

Queryset over M on this handle (same as M::objects(&db)).

Trait Implementations§

Source§

impl Clone for Db

Source§

fn clone(&self) -> Db

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 Db

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Db

§

impl !UnwindSafe for Db

§

impl Freeze for Db

§

impl Send for Db

§

impl Sync for Db

§

impl Unpin for Db

§

impl UnsafeUnpin for Db

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

§

impl<T> Instrument for T

§

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

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

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

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<T> WithSubscriber for T

§

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
§

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

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