pub struct Database { /* private fields */ }Expand description
A handle to a database.
§Examples
use tork_orm_core::Database;
let db = Database::connect("sqlite://app.db", 4).await?;
db.execute("CREATE TABLE t (id INTEGER PRIMARY KEY)".into(), vec![]).await?;Implementations§
Source§impl Database
impl Database
Sourcepub async fn connect(url: &str, max_connections: u32) -> Result<Self>
pub async fn connect(url: &str, max_connections: u32) -> Result<Self>
Connects to a database described by url, with up to max_connections
concurrent connections.
The backend is chosen from the URL scheme: sqlite://... (a bare path or
:memory:) for SQLite, or postgres://... for PostgreSQL when the
postgres feature is enabled.
§Errors
Returns an error if the URL names an unsupported backend or the pool cannot be created.
Sourcepub fn dialect(&self) -> &Arc<dyn Dialect>
pub fn dialect(&self) -> &Arc<dyn Dialect>
Returns the dialect this database renders queries with.
Sourcepub async fn fetch_all(
&self,
sql: String,
params: Vec<Value>,
) -> Result<Vec<Row>>
pub async fn fetch_all( &self, sql: String, params: Vec<Value>, ) -> Result<Vec<Row>>
Runs a row-returning query with bound parameters.
Sourcepub async fn execute(
&self,
sql: String,
params: Vec<Value>,
) -> Result<ExecuteResult>
pub async fn execute( &self, sql: String, params: Vec<Value>, ) -> Result<ExecuteResult>
Runs a statement that returns no rows.
Sourcepub async fn execute_batch(&self, sql: String) -> Result<()>
pub async fn execute_batch(&self, sql: String) -> Result<()>
Runs a batch of semicolon-separated statements with no bound parameters.
Sourcepub fn statement_count(&self) -> u64
pub fn statement_count(&self) -> u64
Returns the number of statements run through this database so far.
Useful in tests to confirm a query strategy (such as preloading adding one query per relation, not one per row).
Source§impl Database
impl Database
Sourcepub async fn transaction<F, R>(&self, f: F) -> Result<R>
pub async fn transaction<F, R>(&self, f: F) -> Result<R>
Runs f inside a transaction, committing on Ok and rolling back on Err.
This is the preferred way to run transactional work. The closure receives a
&Transaction that implements Executor, so every ORM method works
against it without modification.
The future must be boxed because the compiler cannot name the return type
of an async closure; use Box::pin or the transaction! macro from
the tork-orm facade, which adds that boilerplate automatically.
§Examples
use tork_orm_core::{Database, Executor};
let db = Database::connect("sqlite::memory:", 1).await?;
db.execute("CREATE TABLE t (x INTEGER)".into(), vec![]).await?;
db.transaction(|tx| Box::pin(async move {
tx.execute("INSERT INTO t VALUES (1)".into(), vec![]).await?;
tx.execute("INSERT INTO t VALUES (2)".into(), vec![]).await?;
Ok(())
})).await?;§Errors
Returns an error if BEGIN, any statement inside f, or COMMIT fails.
Sourcepub async fn transaction_retry<F, R>(
&self,
max_attempts: u32,
f: F,
) -> Result<R>
pub async fn transaction_retry<F, R>( &self, max_attempts: u32, f: F, ) -> Result<R>
Runs f inside a transaction, retrying up to max_attempts times when it
fails with a transient conflict — a lock timeout, deadlock, or
serialization failure (see OrmError::is_retryable).
Under serializable isolation or heavy write contention the database may
abort a transaction and expect the client to retry. f may run more than
once, so it must be safe to re-run (idempotent in its in-memory effects).
§Examples
use tork_orm_core::{Database, Executor};
let db = Database::connect("sqlite::memory:", 1).await?;
db.transaction_retry(5, |tx| Box::pin(async move {
tx.execute("UPDATE accounts SET balance = balance - 10 WHERE id = 1".into(), vec![]).await?;
Ok(())
})).await?;Sourcepub async fn begin(&self) -> Result<Transaction>
pub async fn begin(&self) -> Result<Transaction>
Opens a new transaction on a pinned connection.
Runs BEGIN on the connection and returns a Transaction handle.
The handle implements Executor, so it can be passed directly to ORM
query methods. Call Transaction::commit to persist the work, or let
the handle drop to roll back automatically.
§Errors
Returns an error if the pool has no connections available or BEGIN
fails.
§Examples
use tork_orm_core::Database;
let db = Database::connect("sqlite::memory:", 1).await?;
let mut tx = db.begin().await?;
db.execute("CREATE TABLE t (x INTEGER)".into(), vec![]).await?;
tx.commit().await?;Sourcepub fn transaction_with(&self) -> TransactionBuilder<'_>
pub fn transaction_with(&self) -> TransactionBuilder<'_>
Returns a TransactionBuilder for opening a transaction with a
specific isolation level.
§Examples
use tork_orm_core::{Database, Executor};
let db = Database::connect("sqlite::memory:", 1).await?;
db.execute("CREATE TABLE t (x INTEGER)".into(), vec![]).await?;
db.transaction_with()
.immediate()
.run(|tx| Box::pin(async move {
tx.execute("INSERT INTO t VALUES (1)".into(), vec![]).await?;
Ok(())
}))
.await?;Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for Database
impl !UnwindSafe for Database
impl Freeze for Database
impl Send for Database
impl Sync for Database
impl Unpin for Database
impl UnsafeUnpin for Database
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<E> DynExecutor for E
impl<E> DynExecutor for E
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the foreground set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red() and
green(), which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg():
use yansi::{Paint, Color};
painted.fg(Color::White);Set foreground color to white using white().
use yansi::Paint;
painted.white();Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the background set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red() and
on_green(), which have the same functionality but
are pithier.
§Example
Set background color to red using fg():
use yansi::{Paint, Color};
painted.bg(Color::Red);Set background color to red using on_red().
use yansi::Paint;
painted.on_red();Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute value.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold() and
underline(), which have the same functionality
but are pithier.
§Example
Make text bold using attr():
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);Make text bold using using bold().
use yansi::Paint;
painted.bold();Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi Quirk value.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask() and
wrap(), which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk():
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);Enable wrapping using wrap().
use yansi::Paint;
painted.wrap();Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
fn clear(&self) -> Painted<&T>
renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted only when both stdout and stderr are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);