kit_rs/database/connection.rs
1//! Database connection management
2
3use sea_orm::{ConnectOptions, Database, DatabaseConnection};
4use std::sync::Arc;
5use std::time::Duration;
6
7use crate::database::config::DatabaseConfig;
8use crate::error::FrameworkError;
9
10/// Wrapper around SeaORM's DatabaseConnection
11///
12/// This provides a clonable, thread-safe connection that can be stored
13/// in the application container and shared across requests.
14///
15/// # Example
16///
17/// ```rust,ignore
18/// let conn = DbConnection::connect(&config).await?;
19///
20/// // Use with SeaORM queries
21/// let users = User::find().all(conn.inner()).await?;
22/// ```
23#[derive(Clone)]
24pub struct DbConnection {
25 inner: Arc<DatabaseConnection>,
26}
27
28impl DbConnection {
29 /// Create a new database connection from config
30 ///
31 /// This establishes a connection pool using the provided configuration.
32 pub async fn connect(config: &DatabaseConfig) -> Result<Self, FrameworkError> {
33 let mut opt = ConnectOptions::new(&config.url);
34 opt.max_connections(config.max_connections)
35 .min_connections(config.min_connections)
36 .connect_timeout(Duration::from_secs(config.connect_timeout))
37 .sqlx_logging(config.logging);
38
39 let conn = Database::connect(opt)
40 .await
41 .map_err(|e| FrameworkError::database(e.to_string()))?;
42
43 Ok(Self {
44 inner: Arc::new(conn),
45 })
46 }
47
48 /// Get a reference to the underlying SeaORM connection
49 ///
50 /// Use this when you need to execute raw SeaORM queries.
51 ///
52 /// # Example
53 ///
54 /// ```rust,ignore
55 /// let conn = DB::connection()?;
56 /// let users = User::find()
57 /// .filter(user::Column::Active.eq(true))
58 /// .all(conn.inner())
59 /// .await?;
60 /// ```
61 pub fn inner(&self) -> &DatabaseConnection {
62 &self.inner
63 }
64
65 /// Check if the connection is closed
66 pub fn is_closed(&self) -> bool {
67 // SeaORM doesn't expose this directly, but we can check via ping
68 false
69 }
70}
71
72impl AsRef<DatabaseConnection> for DbConnection {
73 fn as_ref(&self) -> &DatabaseConnection {
74 &self.inner
75 }
76}
77
78impl std::ops::Deref for DbConnection {
79 type Target = DatabaseConnection;
80
81 fn deref(&self) -> &Self::Target {
82 &self.inner
83 }
84}