pub struct DB;Expand description
Global database access point
Implementations§
Source§impl DB
impl DB
Sourcepub async fn init(database_url: Option<&str>) -> Result<()>
pub async fn init(database_url: Option<&str>) -> Result<()>
Initialize the global database connection from a database URL (legacy)
This method maintains backward compatibility with existing code.
For new applications, consider using init_registry for multi-database support.
§Arguments
database_url- Optional database connection URL. If None, database operations will return errors.
§Examples
// Initialize with MySQL
DB::init(Some("mysql://user:pass@localhost/mydb")).await?;
// Initialize without database (some apps don't need it)
DB::init(None).await?;Sourcepub async fn init_registry(config: DatabasesConfig) -> Result<()>
pub async fn init_registry(config: DatabasesConfig) -> Result<()>
Initialize database registry with multiple databases
This is the new recommended way to initialize databases, supporting multiple named connections.
§Arguments
config- Database configuration with one or more database connections
§Examples
let mut config = DatabasesConfig::new();
config.add_database("primary", DatabaseConnectionConfigBuilder::new()
.url("postgresql://localhost/main")
.max_connections(20)
.build()
.unwrap());
config.add_database("analytics", DatabaseConnectionConfigBuilder::new()
.url("mysql://localhost/analytics")
.max_connections(10)
.build()
.unwrap());
DB::init_registry(config).await?;Sourcepub async fn adapter(name: &str) -> Result<Box<dyn DatabaseAdapter>>
pub async fn adapter(name: &str) -> Result<Box<dyn DatabaseAdapter>>
Get a specific database adapter
Alias for use that doesn’t require the r# prefix
Sourcepub fn query() -> Result<QueryBuilder>
pub fn query() -> Result<QueryBuilder>
Get a query builder for the configured database
Returns a QueryBuilder that’s pre-configured for the current database backend. This maintains backward compatibility with existing code.
§Returns
Ok(QueryBuilder)- Ready-to-use query builderErr(Error)- If database is not initialized or not configured
§Examples
let users = DB::query()?
.from("users")
.where_eq("active", true)
.limit(10)
.build()?;Sourcepub fn connection() -> Option<Arc<AnyDatabase>>
pub fn connection() -> Option<Arc<AnyDatabase>>
Get direct access to the database connection
Returns the underlying AnyDatabase connection for advanced operations.
§Returns
Some(Arc<AnyDatabase>)- Database connection if initializedNone- If no database is configured
Sourcepub async fn get() -> Result<Arc<AnyDatabase>>
pub async fn get() -> Result<Arc<AnyDatabase>>
Get the database connection pool for direct use
This method is for compatibility with code expecting DB::get(). Returns a Result containing the database connection.
§Returns
Ok(Arc<AnyDatabase>)- Database connection if initializedErr(Error)- If database is not configured
Sourcepub fn is_initialized() -> bool
pub fn is_initialized() -> bool
Check if database is initialized and available
§Returns
true- Database is ready for usefalse- Database is not configured or initialization failed
Sourcepub fn backend() -> Option<DatabaseBackend>
pub fn backend() -> Option<DatabaseBackend>
Get the database backend type if initialized
§Returns
Some(DatabaseBackend)- The type of database (Postgres, MySQL, SQLite)None- If database is not initialized
Sourcepub fn pg_pool() -> Result<Arc<PgPool>>
pub fn pg_pool() -> Result<Arc<PgPool>>
Get the PostgreSQL pool if database is PostgreSQL
§Returns
Ok(Arc<sqlx::PgPool>)- PostgreSQL connection pool wrapped in ArcErr(Error)- If database is not configured or is not PostgreSQL
Sourcepub fn mysql_pool() -> Result<Arc<MySqlPool>>
pub fn mysql_pool() -> Result<Arc<MySqlPool>>
Get the MySQL pool if database is MySQL
§Returns
Ok(Arc<sqlx::MySqlPool>)- MySQL connection pool wrapped in ArcErr(Error)- If database is not configured or is not MySQL
Sourcepub fn sqlite_pool() -> Result<Arc<SqlitePool>>
pub fn sqlite_pool() -> Result<Arc<SqlitePool>>
Get the SQLite pool if database is SQLite
§Returns
Ok(Arc<sqlx::SqlitePool>)- SQLite connection pool wrapped in ArcErr(Error)- If database is not configured or is not SQLite
Sourcepub async fn execute_with_params(
sql: &str,
params: Vec<SqlValue>,
) -> Result<u64>
pub async fn execute_with_params( sql: &str, params: Vec<SqlValue>, ) -> Result<u64>
Execute a query with parameters using the appropriate database adapter
This method automatically handles database-specific type conversions through the adapter layer, eliminating the need for database-specific binding code in models.
§Arguments
sql- SQL query to executeparams- Parameters to bind to the query
§Returns
Ok(u64)- Number of rows affectedErr(Error)- If execution fails
Sourcepub async fn fetch_one_with_params(
sql: &str,
params: Vec<SqlValue>,
) -> Result<Option<Value>>
pub async fn fetch_one_with_params( sql: &str, params: Vec<SqlValue>, ) -> Result<Option<Value>>
Sourcepub async fn execute_insert_returning(
sql: &str,
params: Vec<SqlValue>,
table: &str,
id_field: &str,
) -> Result<Option<Value>>
pub async fn execute_insert_returning( sql: &str, params: Vec<SqlValue>, table: &str, id_field: &str, ) -> Result<Option<Value>>
Execute an INSERT query and return the inserted row
This method handles database-specific RETURNING syntax and type conversions. For databases that don’t support RETURNING, it uses alternative methods to fetch the inserted row.
§Arguments
sql- INSERT SQL query (without RETURNING clause)params- Parameters to bind to the querytable- Table name for fallback fetchid_field- Name of the ID field for fallback fetch
§Returns
Ok(Some(JsonValue))- The inserted row as JSONErr(Error)- If insertion fails
Sourcepub async fn ping() -> Result<bool>
pub async fn ping() -> Result<bool>
Test database connectivity
Sends a simple ping/test query to verify the database connection is alive. This is useful for health checks and monitoring.
§Returns
Ok(true)- Database is connected and respondingOk(false)- Database is not configured (no connection URL)Err(Error)- Database is configured but connection test failed
§Examples
// Health check during startup or monitoring
if DB::ping().await? {
println!("Database is healthy");
}Auto Trait Implementations§
impl Freeze for DB
impl RefUnwindSafe for DB
impl Send for DB
impl Sync for DB
impl Unpin for DB
impl UnsafeUnpin for DB
impl UnwindSafe for DB
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<T> ErasedDestructor for Twhere
T: 'static,
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 more