pub struct Database { /* private fields */ }Expand description
Represents a pool of database connections.
This struct provides a thread-safe wrapper around a connection pool, allowing multiple parts of the application to share database connections efficiently. Supports runtime backend selection between PostgreSQL and SQLite.
§Thread Safety
The Database struct is Clone and can be safely shared between threads.
Each clone references the same underlying connection pool.
Implementations§
Source§impl Database
impl Database
Sourcepub fn new(connection_string: &str, database_name: &str, max_size: u32) -> Self
pub fn new(connection_string: &str, database_name: &str, max_size: u32) -> Self
Creates a new database connection pool with automatic backend detection.
The backend is detected from the connection string:
postgres://orpostgresql://-> PostgreSQLsqlite://, file paths, or:memory:-> SQLite
§Arguments
connection_string- The database connection URL or pathdatabase_name- The database name (used for PostgreSQL, ignored for SQLite)max_size- Maximum number of connections in the pool
§Panics
Panics if the connection pool cannot be created.
Sourcepub fn new_with_schema(
connection_string: &str,
database_name: &str,
max_size: u32,
schema: Option<&str>,
) -> Self
pub fn new_with_schema( connection_string: &str, database_name: &str, max_size: u32, schema: Option<&str>, ) -> Self
Creates a new database connection pool with optional schema support.
The backend is detected from the connection string. Schema support is only effective for PostgreSQL; the schema parameter is stored but ignored for SQLite.
§Arguments
connection_string- The database connection URL or pathdatabase_name- The database name (used for PostgreSQL, ignored for SQLite)max_size- Maximum number of connections in the poolschema- Optional schema name for PostgreSQL multi-tenant isolation
§Panics
Panics if connection pool creation fails or if the schema name is invalid.
Use try_new_with_schema for fallible construction.
Sourcepub fn try_new_with_schema(
connection_string: &str,
_database_name: &str,
max_size: u32,
schema: Option<&str>,
) -> Result<Self, DatabaseError>
pub fn try_new_with_schema( connection_string: &str, _database_name: &str, max_size: u32, schema: Option<&str>, ) -> Result<Self, DatabaseError>
Creates a new database connection pool with optional schema support.
This is the fallible version of new_with_schema.
§Arguments
connection_string- The database connection URL or pathdatabase_name- The database name (used for PostgreSQL, ignored for SQLite)max_size- Maximum number of connections in the poolschema- Optional schema name for PostgreSQL multi-tenant isolation
§Errors
Returns an error if:
- The schema name is invalid (SQL injection prevention)
- The connection pool cannot be created
Sourcepub fn backend(&self) -> BackendType
pub fn backend(&self) -> BackendType
Returns the detected backend type.
Sourcepub fn get_connection(&self) -> AnyPool
pub fn get_connection(&self) -> AnyPool
Alias for pool() for backward compatibility.
Sourcepub fn close(&self)
pub fn close(&self)
Closes the connection pool, releasing all database connections.
After calling this method, all current and future attempts to get connections from the pool will fail immediately. This should be called when shutting down to ensure connections are properly released back to the database server.
§Example
let db = Database::new("postgres://localhost/mydb", "mydb", 10)?;
// ... use database ...
db.close(); // Release all connectionsSourcepub async fn run_migrations(&self) -> Result<(), String>
pub async fn run_migrations(&self) -> Result<(), String>
Runs pending database migrations for the appropriate backend.
This method detects the backend type and runs the corresponding migrations.
Sourcepub async fn setup_schema(&self, schema: &str) -> Result<(), String>
pub async fn setup_schema(&self, schema: &str) -> Result<(), String>
Sets up the PostgreSQL schema for multi-tenant isolation.
Creates the schema if it doesn’t exist and runs migrations within it. Returns an error if called on a SQLite backend or if the schema name is invalid (to prevent SQL injection).
§Security
Schema names are validated to prevent SQL injection attacks. Only alphanumeric characters and underscores are allowed.
Sourcepub async fn get_connection_with_schema(
&self,
) -> Result<Object<PgManager>, PoolError<Error>>
pub async fn get_connection_with_schema( &self, ) -> Result<Object<PgManager>, PoolError<Error>>
Gets a PostgreSQL connection with the schema search path set.
For PostgreSQL, this sets the search path to the configured schema. For SQLite, this is a no-op and returns an error.
§Security
Schema names are validated before use in SQL to prevent injection attacks.
Sourcepub async fn get_postgres_connection(
&self,
) -> Result<Object<PgManager>, PoolError<Error>>
pub async fn get_postgres_connection( &self, ) -> Result<Object<PgManager>, PoolError<Error>>
Gets a PostgreSQL connection.
Returns an error if this is a SQLite backend.
Sourcepub async fn get_sqlite_connection(
&self,
) -> Result<Object<SqliteManager>, PoolError<Error>>
pub async fn get_sqlite_connection( &self, ) -> Result<Object<SqliteManager>, PoolError<Error>>
Gets a SQLite connection.
Returns an error if this is a PostgreSQL backend.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Database
impl !RefUnwindSafe for Database
impl Send for Database
impl Sync for Database
impl Unpin for Database
impl !UnwindSafe for Database
Blanket Implementations§
Source§impl<T> AggregateExpressionMethods for T
impl<T> AggregateExpressionMethods for T
Source§fn aggregate_distinct(self) -> Self::Outputwhere
Self: DistinctDsl,
fn aggregate_distinct(self) -> Self::Outputwhere
Self: DistinctDsl,
DISTINCT modifier for aggregate functions Read moreSource§fn aggregate_all(self) -> Self::Outputwhere
Self: AllDsl,
fn aggregate_all(self) -> Self::Outputwhere
Self: AllDsl,
ALL modifier for aggregate functions Read moreSource§fn aggregate_filter<P>(self, f: P) -> Self::Output
fn aggregate_filter<P>(self, f: P) -> Self::Output
Source§fn aggregate_order<O>(self, o: O) -> Self::Outputwhere
Self: OrderAggregateDsl<O>,
fn aggregate_order<O>(self, o: O) -> Self::Outputwhere
Self: OrderAggregateDsl<O>,
§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§unsafe fn clone_to_uninit(&self, dest: *mut u8)
unsafe fn clone_to_uninit(&self, dest: *mut u8)
clone_to_uninit)Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
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> IntoSql for T
impl<T> IntoSql for T
Source§fn into_sql<T>(self) -> Self::Expression
fn into_sql<T>(self) -> Self::Expression
self to an expression for Diesel’s query builder. Read moreSource§fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
&self to an expression for Diesel’s query builder. Read more