pub struct DatabaseConnection { /* private fields */ }database and native only.Expand description
Database connection wrapper
Implementations§
Source§impl DatabaseConnection
impl DatabaseConnection
Sourcepub fn new(backend: Arc<dyn DatabaseBackend>) -> DatabaseConnection
pub fn new(backend: Arc<dyn DatabaseBackend>) -> DatabaseConnection
Creates a new instance.
Defaults to is_cockroachdb = false, which is the correct choice when
the caller has not (or cannot) probe the server. If the supplied backend
is known to be CockroachDB, use Self::new_with_flavor instead so the
migration recorder routes through the sentinel-row lock path rather than
pg_advisory_lock (issue #4642).
Sourcepub fn new_with_flavor(
backend: Arc<dyn DatabaseBackend>,
is_cockroachdb: bool,
) -> DatabaseConnection
pub fn new_with_flavor( backend: Arc<dyn DatabaseBackend>, is_cockroachdb: bool, ) -> DatabaseConnection
Creates a new instance with an explicit CockroachDB flavor flag.
Use this when wrapping an externally constructed Postgres backend whose
flavor is already known — e.g. tests that mount a CockroachDB pool, or
adapters that pre-probe SELECT version() themselves.
Sourcepub async fn connect_postgres(
url: &str,
) -> Result<DatabaseConnection, DatabaseError>
Available on crate feature postgres only.
pub async fn connect_postgres( url: &str, ) -> Result<DatabaseConnection, DatabaseError>
postgres only.Connects to postgres.
Sourcepub async fn connect_postgres_with_pool_size(
url: &str,
pool_size: Option<u32>,
) -> Result<DatabaseConnection, DatabaseError>
Available on crate feature postgres only.
pub async fn connect_postgres_with_pool_size( url: &str, pool_size: Option<u32>, ) -> Result<DatabaseConnection, DatabaseError>
postgres only.Connects to postgres with pool size.
Sourcepub async fn connect_postgres_or_create(
url: &str,
) -> Result<DatabaseConnection, DatabaseError>
Available on crate feature postgres only.
pub async fn connect_postgres_or_create( url: &str, ) -> Result<DatabaseConnection, DatabaseError>
postgres only.Connect to PostgreSQL with automatic database creation if it doesn’t exist.
This method first attempts to connect to the specified database. If the connection fails due to the database not existing, it will:
- Connect to the default
postgresdatabase - Create the target database
- Reconnect to the newly created database
§Arguments
url- PostgreSQL connection URL (e.g., “postgres://user:pass@localhost/mydb”)
§Example
use reinhardt_db::backends::connection::DatabaseConnection;
// Will create 'mydb' if it doesn't exist
let conn = DatabaseConnection::connect_postgres_or_create(
"postgres://postgres@localhost/mydb"
).await?;Sourcepub async fn connect_postgres_or_create_with_pool_size(
url: &str,
pool_size: Option<u32>,
) -> Result<DatabaseConnection, DatabaseError>
Available on crate feature postgres only.
pub async fn connect_postgres_or_create_with_pool_size( url: &str, pool_size: Option<u32>, ) -> Result<DatabaseConnection, DatabaseError>
postgres only.Connect to PostgreSQL with automatic database creation and custom pool size.
See Self::connect_postgres_or_create for details on automatic database creation.
Sourcepub async fn connect_sqlite(
url: &str,
) -> Result<DatabaseConnection, DatabaseError>
Available on crate feature sqlite only.
pub async fn connect_sqlite( url: &str, ) -> Result<DatabaseConnection, DatabaseError>
sqlite only.Connects to a SQLite database at the given URL.
Sourcepub fn from_sqlite_pool(pool: Pool<Sqlite>) -> DatabaseConnection
Available on crate feature sqlite only.
pub fn from_sqlite_pool(pool: Pool<Sqlite>) -> DatabaseConnection
sqlite only.Creates a connection from an existing SQLite pool.
Sourcepub async fn connect_mysql(
url: &str,
) -> Result<DatabaseConnection, DatabaseError>
Available on crate feature mysql only.
pub async fn connect_mysql( url: &str, ) -> Result<DatabaseConnection, DatabaseError>
mysql only.Connects to a MySQL database at the given URL.
Sourcepub fn backend(&self) -> Arc<dyn DatabaseBackend> ⓘ
pub fn backend(&self) -> Arc<dyn DatabaseBackend> ⓘ
Performs the backend operation.
Sourcepub fn database_type(&self) -> DatabaseType
pub fn database_type(&self) -> DatabaseType
Get the database type
Sourcepub fn is_cockroachdb(&self) -> bool
pub fn is_cockroachdb(&self) -> bool
Returns true when the underlying server is CockroachDB.
CockroachDB is wire-compatible with PostgreSQL and uses the same
PostgresBackend, so database_type() returns DatabaseType::Postgres
for both. Callers that must dispatch on the server flavour (e.g. the
migration-lock path, which cannot use pg_advisory_lock on CockroachDB —
see issue #4642) should check this flag first.
The flag is determined at connection time via a single SELECT version()
probe and is false for any non-Postgres backend.
Sourcepub fn insert(&self, table: impl Into<String>) -> InsertBuilder
pub fn insert(&self, table: impl Into<String>) -> InsertBuilder
Performs the insert operation.
Sourcepub fn update(&self, table: impl Into<String>) -> UpdateBuilder
pub fn update(&self, table: impl Into<String>) -> UpdateBuilder
Performs the update operation.
Sourcepub fn select(&self) -> SelectBuilder
pub fn select(&self) -> SelectBuilder
Performs the select operation.
Sourcepub fn delete(&self, table: impl Into<String>) -> DeleteBuilder
pub fn delete(&self, table: impl Into<String>) -> DeleteBuilder
Performs the delete operation.
Sourcepub fn database_url_from<S>(
settings: &S,
env_override: Option<&str>,
) -> Result<String, DatabaseError>where
S: HasCoreSettings + ?Sized,
Available on crate feature settings only.
pub fn database_url_from<S>(
settings: &S,
env_override: Option<&str>,
) -> Result<String, DatabaseError>where
S: HasCoreSettings + ?Sized,
settings only.Resolve a database URL from an already-built composed settings value.
This is the preferred entry point for callers that already hold a
ProjectSettings (or any type that implements
reinhardt_conf::HasCoreSettings). It reads the default entry of
CoreSettings::databases and converts it to a URL via
DatabaseConfig::to_url.
The optional env_override argument is honored first: if it is
Some(url), that URL is returned verbatim. Pass None to skip the
override entirely. To opt into the env-var short circuit, bind the
result of std::env::var first so the temporary String outlives
the borrow:
let database_url_env = std::env::var("DATABASE_URL").ok();
let url = DatabaseConnection::database_url_from(
settings,
database_url_env.as_deref(),
)?;§Errors
Returns a ConnectionError if the core.databases.default entry is
missing from the composed settings. DatabaseConfig::to_url itself
is infallible, so a successfully resolved default entry always
yields Ok(_).
§Example
use reinhardt_db::backends::connection::DatabaseConnection;
let url = DatabaseConnection::database_url_from(settings, None)
.expect("database url");Sourcepub fn get_database_url_from_env_or_settings(
base_dir: Option<PathBuf>,
) -> Result<String, DatabaseError>
👎Deprecated since 0.1.0-rc.29: use DatabaseConnection::database_url_from with a pre-built ProjectSettings instead
Available on crate feature settings only.
pub fn get_database_url_from_env_or_settings( base_dir: Option<PathBuf>, ) -> Result<String, DatabaseError>
use DatabaseConnection::database_url_from with a pre-built ProjectSettings instead
settings only.Get database URL from environment variable or settings files
This function first checks the DATABASE_URL environment variable.
If not found, it attempts to load database configuration from settings files
in the settings/ directory.
§Arguments
base_dir- Base directory for the project (defaults to current directory if None)
§Returns
Returns the database URL string, or an error if neither environment variable nor settings configuration is found.
§Deprecated
This function reloads settings/<profile>.toml from disk every time it
is invoked, which is wasteful and duplicates settings-loading logic. Use
Self::database_url_from with an already-built ProjectSettings
instead.
§Example
use reinhardt_db::backends::connection::DatabaseConnection;
let url = DatabaseConnection::get_database_url_from_env_or_settings(None)?;
let conn = DatabaseConnection::connect_sqlite(&url).await?;Sourcepub async fn execute(
&self,
sql: &str,
params: Vec<QueryValue>,
) -> Result<QueryResult, DatabaseError>
pub async fn execute( &self, sql: &str, params: Vec<QueryValue>, ) -> Result<QueryResult, DatabaseError>
Executes the operation.
Sourcepub async fn fetch_one(
&self,
sql: &str,
params: Vec<QueryValue>,
) -> Result<Row, DatabaseError>
pub async fn fetch_one( &self, sql: &str, params: Vec<QueryValue>, ) -> Result<Row, DatabaseError>
Fetches one.
Sourcepub async fn fetch_all(
&self,
sql: &str,
params: Vec<QueryValue>,
) -> Result<Vec<Row>, DatabaseError>
pub async fn fetch_all( &self, sql: &str, params: Vec<QueryValue>, ) -> Result<Vec<Row>, DatabaseError>
Fetches all.
Sourcepub async fn fetch_optional(
&self,
sql: &str,
params: Vec<QueryValue>,
) -> Result<Option<Row>, DatabaseError>
pub async fn fetch_optional( &self, sql: &str, params: Vec<QueryValue>, ) -> Result<Option<Row>, DatabaseError>
Fetches optional.
Sourcepub async fn begin(&self) -> Result<Box<dyn TransactionExecutor>, DatabaseError>
pub async fn begin(&self) -> Result<Box<dyn TransactionExecutor>, DatabaseError>
Begin a database transaction and return a dedicated executor
This method acquires a dedicated database connection and begins a
transaction on it. All queries executed through the returned
TransactionExecutor are guaranteed to run on the same physical
connection, ensuring proper transaction isolation.
§Returns
A boxed TransactionExecutor that holds the dedicated connection
and provides methods for executing queries within the transaction.
§Example
use reinhardt_db::backends::connection::DatabaseConnection;
let conn = DatabaseConnection::connect_postgres("postgres://localhost/mydb").await?;
let mut tx = conn.begin().await?;
tx.execute("INSERT INTO users (name) VALUES ($1)", vec!["Alice".into()]).await?;
tx.commit().await?;Sourcepub async fn begin_with_isolation(
&self,
level: IsolationLevel,
) -> Result<Box<dyn TransactionExecutor>, DatabaseError>
pub async fn begin_with_isolation( &self, level: IsolationLevel, ) -> Result<Box<dyn TransactionExecutor>, DatabaseError>
Begin a transaction with a specific isolation level
§Examples
use reinhardt_db::backends::connection::DatabaseConnection;
use reinhardt_db::backends::types::IsolationLevel;
let conn = DatabaseConnection::connect_postgres("postgres://localhost/mydb").await?;
let mut tx = conn.begin_with_isolation(IsolationLevel::Serializable).await?;
tx.execute("INSERT INTO users (name) VALUES ($1)", vec!["Alice".into()]).await?;
tx.commit().await?;Sourcepub fn into_postgres(&self) -> Option<Pool<Postgres>>
Available on crate feature postgres only.
pub fn into_postgres(&self) -> Option<Pool<Postgres>>
postgres only.Converts into postgres.
Sourcepub fn into_sqlite(&self) -> Option<Pool<Sqlite>>
Available on crate feature sqlite only.
pub fn into_sqlite(&self) -> Option<Pool<Sqlite>>
sqlite only.Converts into the underlying SQLite pool, if the backend is SQLite.
Sourcepub fn into_mysql(&self) -> Option<Pool<MySql>>
Available on crate feature mysql only.
pub fn into_mysql(&self) -> Option<Pool<MySql>>
mysql only.Converts into the underlying MySQL pool, if the backend is MySQL.
Trait Implementations§
Source§impl Clone for DatabaseConnection
impl Clone for DatabaseConnection
Source§fn clone(&self) -> DatabaseConnection
fn clone(&self) -> DatabaseConnection
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Injectable for DatabaseConnection
Injectable implementation for DatabaseConnection
impl Injectable for DatabaseConnection
Injectable implementation for DatabaseConnection
DatabaseConnection must be explicitly registered in the DI context using
InjectionContextBuilder::singleton(). It cannot be auto-injected because
it requires runtime configuration (connection URL, pool settings, etc.).
§Example
use reinhardt_di::{InjectionContext, SingletonScope};
use reinhardt_db::backends::DatabaseConnection;
use std::sync::Arc;
// Create and configure the connection
let db = DatabaseConnection::connect_postgres("postgres://localhost/mydb")
.await
.expect("Failed to connect to database");
// Register in DI context
let singleton_scope = Arc::new(SingletonScope::new());
let ctx = InjectionContext::builder(singleton_scope)
.singleton(db)
.build();
Source§fn inject<'life0, 'async_trait>(
ctx: &'life0 InjectionContext,
) -> Pin<Box<dyn Future<Output = Result<DatabaseConnection, DiError>> + Send + 'async_trait>>where
'life0: 'async_trait,
DatabaseConnection: 'async_trait,
fn inject<'life0, 'async_trait>(
ctx: &'life0 InjectionContext,
) -> Pin<Box<dyn Future<Output = Result<DatabaseConnection, DiError>> + Send + 'async_trait>>where
'life0: 'async_trait,
DatabaseConnection: 'async_trait,
Source§fn inject_uncached<'life0, 'async_trait>(
ctx: &'life0 InjectionContext,
) -> Pin<Box<dyn Future<Output = Result<DatabaseConnection, DiError>> + Send + 'async_trait>>where
'life0: 'async_trait,
DatabaseConnection: 'async_trait,
fn inject_uncached<'life0, 'async_trait>(
ctx: &'life0 InjectionContext,
) -> Pin<Box<dyn Future<Output = Result<DatabaseConnection, DiError>> + Send + 'async_trait>>where
'life0: 'async_trait,
DatabaseConnection: 'async_trait,
cache = false support). Read moreAuto Trait Implementations§
impl Freeze for DatabaseConnection
impl !RefUnwindSafe for DatabaseConnection
impl Send for DatabaseConnection
impl Sync for DatabaseConnection
impl Unpin for DatabaseConnection
impl UnsafeUnpin for DatabaseConnection
impl !UnwindSafe for DatabaseConnection
Blanket Implementations§
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.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> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::RequestSource§impl<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
type Err = Infallible
fn into_result(self) -> Result<T, <T as IntoResult<T>>::Err>
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.