Skip to main content

DB

Struct DB 

Source
pub struct DB;
Expand description

Global database access point

Implementations§

Source§

impl DB

Source

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?;
Source

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?;
Source

pub async fn use(name: &str) -> Result<Box<dyn DatabaseAdapter>>

Use a specific named database

§Arguments
  • name - Name of the database to use
§Returns

A database handle that can be used to execute queries

§Examples
let users = DB::r#use("analytics")
    .await?
    .query()
    .from("users")
    .where_eq("active", true)
    .build()?;
Source

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

Source

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 builder
  • Err(Error) - If database is not initialized or not configured
§Examples
let users = DB::query()?
    .from("users")
    .where_eq("active", true)
    .limit(10)
    .build()?;
Source

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 initialized
  • None - If no database is configured
Source

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 initialized
  • Err(Error) - If database is not configured
Source

pub fn is_initialized() -> bool

Check if database is initialized and available

§Returns
  • true - Database is ready for use
  • false - Database is not configured or initialization failed
Source

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
Source

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 Arc
  • Err(Error) - If database is not configured or is not PostgreSQL
Source

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 Arc
  • Err(Error) - If database is not configured or is not MySQL
Source

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 Arc
  • Err(Error) - If database is not configured or is not SQLite
Source

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 execute
  • params - Parameters to bind to the query
§Returns
  • Ok(u64) - Number of rows affected
  • Err(Error) - If execution fails
Source

pub async fn fetch_all_with_params( sql: &str, params: Vec<SqlValue>, ) -> Result<Vec<Value>>

Fetch all rows from a query with parameters

Returns results as JSON values for flexibility.

§Arguments
  • sql - SQL query to execute
  • params - Parameters to bind to the query
§Returns
  • Ok(Vec<serde_json::Value>) - Query results as JSON
  • Err(Error) - If execution fails
Source

pub async fn fetch_one_with_params( sql: &str, params: Vec<SqlValue>, ) -> Result<Option<Value>>

Fetch one row from a query with parameters

Returns result as JSON value for flexibility.

§Arguments
  • sql - SQL query to execute
  • params - Parameters to bind to the query
§Returns
  • Ok(Option<serde_json::Value>) - Query result as JSON if found
  • Err(Error) - If execution fails
Source

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 query
  • table - Table name for fallback fetch
  • id_field - Name of the ID field for fallback fetch
§Returns
  • Ok(Some(JsonValue)) - The inserted row as JSON
  • Err(Error) - If insertion fails
Source

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 responding
  • Ok(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");
}
Source

pub async fn shutdown() -> Result<()>

Gracefully close all database connections

This method should be called during application shutdown to ensure all database connections are properly closed and resources are released.

§Examples
// During application shutdown
DB::shutdown().await?;

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> 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> ErasedDestructor for T
where T: 'static,

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> Same for T

Source§

type Output = T

Should always be Self
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