Skip to main content

larastvel_core/database/
mod.rs

1use std::future::Future;
2use std::sync::Arc;
3
4use sea_orm::{ConnectOptions, Database, DbConn, TransactionTrait};
5use sea_orm_migration::MigratorTrait;
6use tokio::sync::RwLock;
7use tracing::info;
8
9use crate::config::Config;
10
11#[async_trait::async_trait]
12pub trait Seeder {
13    fn name() -> &'static str;
14    async fn run(conn: &DbConn) -> Result<(), Box<dyn std::error::Error>>;
15}
16
17pub struct DatabaseSeeder;
18
19impl DatabaseSeeder {
20    pub async fn run_all(_conn: &DbConn) -> Result<(), Box<dyn std::error::Error>> {
21        info!("Running database seeders");
22        Ok(())
23    }
24
25    pub async fn run_seeder<S: Seeder>(conn: &DbConn) -> Result<(), Box<dyn std::error::Error>> {
26        info!("Running seeder: {}", S::name());
27        S::run(conn).await
28    }
29}
30
31#[derive(Clone)]
32pub struct DatabaseManager {
33    conn: Arc<RwLock<Option<DbConn>>>,
34    config: Config,
35}
36
37impl DatabaseManager {
38    pub fn new(config: &Config) -> Self {
39        Self {
40            conn: Arc::new(RwLock::new(None)),
41            config: config.clone(),
42        }
43    }
44
45    pub async fn connect(&self) -> Result<DbConn, sea_orm::DbErr> {
46        if let Some(conn) = self.conn.read().await.as_ref() {
47            return Ok(conn.clone());
48        }
49
50        let url = self.build_url();
51        info!("Connecting to database: {}", &self.config.database.driver);
52
53        let mut opt = ConnectOptions::new(url);
54        opt.max_connections(100)
55            .min_connections(5)
56            .connect_timeout(std::time::Duration::from_secs(10))
57            .idle_timeout(std::time::Duration::from_secs(600))
58            .sqlx_logging(self.config.app.debug);
59
60        let conn = Database::connect(opt).await?;
61        *self.conn.write().await = Some(conn.clone());
62        Ok(conn)
63    }
64
65    pub async fn connection(&self) -> Result<DbConn, sea_orm::DbErr> {
66        self.connect().await
67    }
68
69    /// Run a closure inside a database transaction.
70    ///
71    /// If the closure returns `Ok`, the transaction is committed. If it
72    /// returns `Err`, the transaction is rolled back and the error is
73    /// propagated. The closure must be boxed with `Box::pin` because it
74    /// borrows the transaction handle:
75    ///
76    /// ```rust,ignore
77    /// let ok = db.transaction(|txn| Box::pin(async move {
78    ///     Order::insert_into(txn).await?;
79    ///     Ok(())
80    /// })).await?;
81    /// ```
82    pub async fn transaction<F, T>(&self, f: F) -> Result<T, sea_orm::DbErr>
83    where
84        F: for<'a> FnOnce(
85                &'a sea_orm::DatabaseTransaction,
86            ) -> std::pin::Pin<
87                Box<dyn Future<Output = Result<T, sea_orm::DbErr>> + Send + 'a>,
88            > + Send,
89        T: Send,
90    {
91        let conn = self.connect().await?;
92        let txn = conn.begin().await?;
93        match f(&txn).await {
94            Ok(value) => {
95                txn.commit().await?;
96                Ok(value)
97            }
98            Err(e) => {
99                let _ = txn.rollback().await;
100                Err(e)
101            }
102        }
103    }
104
105    /// Begin a new database transaction and return a handle to it.
106    ///
107    /// The caller is responsible for calling `commit()` or `rollback()`.
108    ///
109    /// ```rust,ignore
110    /// let txn = db.begin_transaction().await?;
111    /// // ... run queries via `txn` (it implements `ConnectionTrait`) ...
112    /// txn.commit().await?;
113    /// ```
114    pub async fn begin_transaction(&self) -> Result<sea_orm::DatabaseTransaction, sea_orm::DbErr> {
115        let conn = self.connect().await?;
116        conn.begin().await
117    }
118
119    pub async fn disconnect(&self) {
120        *self.conn.write().await = None;
121    }
122
123    fn build_url(&self) -> String {
124        let db = &self.config.database;
125        match db.driver.as_str() {
126            "postgres" | "pgsql" => {
127                format!(
128                    "postgres://{}:{}@{}:{}/{}",
129                    db.username, db.password, db.host, db.port, db.database
130                )
131            }
132            "mysql" | "mariadb" => {
133                format!(
134                    "mysql://{}:{}@{}:{}/{}",
135                    db.username, db.password, db.host, db.port, db.database
136                )
137            }
138            "sqlite" => {
139                if db.database == ":memory:" {
140                    "sqlite::memory:".to_string()
141                } else {
142                    format!("sqlite://{}?mode=rwc", db.database)
143                }
144            }
145            _ => {
146                if db.database == ":memory:" {
147                    "sqlite::memory:".to_string()
148                } else {
149                    format!("sqlite://{}?mode=rwc", db.database)
150                }
151            }
152        }
153    }
154
155    pub async fn migrate<M: MigratorTrait>(&self) -> Result<(), sea_orm::DbErr> {
156        let conn = self.connect().await?;
157        info!("Running database migrations");
158        M::up(&conn, None).await
159    }
160
161    pub async fn migrate_fresh<M: MigratorTrait>(&self) -> Result<(), sea_orm::DbErr> {
162        let conn = self.connect().await?;
163        info!("Running fresh database migrations (dropping all tables)");
164        M::fresh(&conn).await
165    }
166
167    pub async fn migrate_rollback<M: MigratorTrait>(
168        &self,
169        steps: Option<u32>,
170    ) -> Result<(), sea_orm::DbErr> {
171        let conn = self.connect().await?;
172        info!("Rolling back database migrations");
173        M::down(&conn, steps).await
174    }
175
176    pub async fn migrate_status<M: MigratorTrait>(&self) -> Result<(), sea_orm::DbErr> {
177        let conn = self.connect().await?;
178        M::status(&conn).await
179    }
180
181    pub async fn seed<S: Seeder>(&self) -> Result<(), Box<dyn std::error::Error>> {
182        let conn = self.connect().await?;
183        DatabaseSeeder::run_seeder::<S>(&conn).await
184    }
185
186    pub async fn seed_all(&self) -> Result<(), Box<dyn std::error::Error>> {
187        let conn = self.connect().await?;
188        DatabaseSeeder::run_all(&conn).await
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    struct TestSeeder;
197
198    #[async_trait::async_trait]
199    impl Seeder for TestSeeder {
200        fn name() -> &'static str {
201            "test_seeder"
202        }
203
204        async fn run(_conn: &DbConn) -> Result<(), Box<dyn std::error::Error>> {
205            Ok(())
206        }
207    }
208
209    #[test]
210    fn test_seeder_trait_compiles() {
211        assert_eq!(TestSeeder::name(), "test_seeder");
212    }
213
214    #[test]
215    fn test_database_seeder_static_methods_exist() {
216        // Verify associated functions compile and are callable
217        let _ = DatabaseSeeder::run_all;
218        let _ = DatabaseSeeder::run_seeder::<TestSeeder>;
219    }
220
221    // -----------------------------------------------------------------------
222    // #[seeder] macro tests
223    // -----------------------------------------------------------------------
224
225    use larastvel_macros::seeder;
226
227    #[seeder("custom_name")]
228    struct CustomSeeder;
229
230    impl CustomSeeder {
231        async fn seed(_conn: &DbConn) -> Result<(), Box<dyn std::error::Error>> {
232            Ok(())
233        }
234    }
235
236    #[seeder]
237    struct AutoNameSeeder;
238
239    impl AutoNameSeeder {
240        async fn seed(_conn: &DbConn) -> Result<(), Box<dyn std::error::Error>> {
241            Ok(())
242        }
243    }
244
245    #[test]
246    fn test_seeder_macro_custom_name() {
247        assert_eq!(CustomSeeder::name(), "custom_name");
248    }
249
250    #[test]
251    fn test_seeder_macro_auto_name() {
252        assert_eq!(AutoNameSeeder::name(), "auto_name_seeder");
253    }
254
255    #[test]
256    fn test_seeder_macro_implements_trait() {
257        // Verify the type satisfies Seeder bounds at compile time
258        fn assert_seeder<S: Seeder>() {}
259        assert_seeder::<CustomSeeder>();
260        assert_seeder::<AutoNameSeeder>();
261    }
262
263    // -----------------------------------------------------------------------
264    // Transaction tests
265    // -----------------------------------------------------------------------
266
267    use sea_orm::{ConnectionTrait, Statement};
268
269    fn sqlite_manager() -> DatabaseManager {
270        let mut config = Config::default();
271        config.database.driver = "sqlite".to_string();
272        config.database.database = ":memory:".to_string();
273        DatabaseManager::new(&config)
274    }
275
276    #[tokio::test]
277    async fn test_transaction_commits() {
278        let db = sqlite_manager();
279        db.transaction(|txn| {
280            Box::pin(async move {
281                txn.execute(Statement::from_string(
282                    sea_orm::DatabaseBackend::Sqlite,
283                    "CREATE TABLE tx_items (id INTEGER PRIMARY KEY, name TEXT)".to_string(),
284                ))
285                .await?;
286                txn.execute(Statement::from_sql_and_values(
287                    sea_orm::DatabaseBackend::Sqlite,
288                    "INSERT INTO tx_items (name) VALUES (?1)",
289                    ["committed".into()],
290                ))
291                .await?;
292                Ok(())
293            })
294        })
295        .await
296        .unwrap();
297
298        let conn = db.connection().await.unwrap();
299        let row = conn
300            .query_one(Statement::from_string(
301                sea_orm::DatabaseBackend::Sqlite,
302                "SELECT COUNT(*) FROM tx_items".to_string(),
303            ))
304            .await
305            .unwrap()
306            .unwrap();
307        let count: i64 = row.try_get_by_index(0).unwrap();
308        assert_eq!(count, 1, "committed transaction should persist the insert");
309    }
310
311    #[tokio::test]
312    async fn test_transaction_rolls_back_on_error() {
313        let db = sqlite_manager();
314        db.connection()
315            .await
316            .unwrap()
317            .execute(Statement::from_string(
318                sea_orm::DatabaseBackend::Sqlite,
319                "CREATE TABLE tx_items (id INTEGER PRIMARY KEY, name TEXT)".to_string(),
320            ))
321            .await
322            .unwrap();
323
324        let result = db
325            .transaction(|txn| {
326                Box::pin(async move {
327                    txn.execute(Statement::from_sql_and_values(
328                        sea_orm::DatabaseBackend::Sqlite,
329                        "INSERT INTO tx_items (name) VALUES (?1)",
330                        ["rolled_back".into()],
331                    ))
332                    .await?;
333                    Err::<(), sea_orm::DbErr>(sea_orm::DbErr::Custom("boom".to_string()))
334                })
335            })
336            .await;
337
338        assert!(result.is_err(), "the error should propagate");
339
340        let conn = db.connection().await.unwrap();
341        let row = conn
342            .query_one(Statement::from_string(
343                sea_orm::DatabaseBackend::Sqlite,
344                "SELECT COUNT(*) FROM tx_items".to_string(),
345            ))
346            .await
347            .unwrap()
348            .unwrap();
349        let count: i64 = row.try_get_by_index(0).unwrap();
350        assert_eq!(count, 0, "rolled-back transaction must not persist changes");
351    }
352
353    #[tokio::test]
354    async fn test_begin_transaction_manual_commit() {
355        let db = sqlite_manager();
356        let txn = db.begin_transaction().await.unwrap();
357        txn.execute(Statement::from_string(
358            sea_orm::DatabaseBackend::Sqlite,
359            "CREATE TABLE tx_items (id INTEGER PRIMARY KEY, name TEXT)".to_string(),
360        ))
361        .await
362        .unwrap();
363        txn.execute(Statement::from_sql_and_values(
364            sea_orm::DatabaseBackend::Sqlite,
365            "INSERT INTO tx_items (name) VALUES (?1)",
366            ["manual".into()],
367        ))
368        .await
369        .unwrap();
370        txn.commit().await.unwrap();
371
372        let conn = db.connection().await.unwrap();
373        let row = conn
374            .query_one(Statement::from_string(
375                sea_orm::DatabaseBackend::Sqlite,
376                "SELECT COUNT(*) FROM tx_items".to_string(),
377            ))
378            .await
379            .unwrap()
380            .unwrap();
381        let count: i64 = row.try_get_by_index(0).unwrap();
382        assert_eq!(count, 1);
383    }
384
385    #[tokio::test]
386    async fn test_begin_transaction_manual_rollback() {
387        let db = sqlite_manager();
388        db.connection()
389            .await
390            .unwrap()
391            .execute(Statement::from_string(
392                sea_orm::DatabaseBackend::Sqlite,
393                "CREATE TABLE tx_items (id INTEGER PRIMARY KEY, name TEXT)".to_string(),
394            ))
395            .await
396            .unwrap();
397
398        let txn = db.begin_transaction().await.unwrap();
399        txn.execute(Statement::from_sql_and_values(
400            sea_orm::DatabaseBackend::Sqlite,
401            "INSERT INTO tx_items (name) VALUES (?1)",
402            ["aborted".into()],
403        ))
404        .await
405        .unwrap();
406        txn.rollback().await.unwrap();
407
408        let conn = db.connection().await.unwrap();
409        let row = conn
410            .query_one(Statement::from_string(
411                sea_orm::DatabaseBackend::Sqlite,
412                "SELECT COUNT(*) FROM tx_items".to_string(),
413            ))
414            .await
415            .unwrap()
416            .unwrap();
417        let count: i64 = row.try_get_by_index(0).unwrap();
418        assert_eq!(count, 0);
419    }
420
421    #[tokio::test]
422    async fn test_transaction_sequential_commits() {
423        let db = sqlite_manager();
424        for name in ["first", "second"] {
425            db.transaction(|txn| {
426                Box::pin(async move {
427                    txn.execute(Statement::from_string(
428                        sea_orm::DatabaseBackend::Sqlite,
429                        "CREATE TABLE IF NOT EXISTS tx_items (id INTEGER PRIMARY KEY, name TEXT)"
430                            .to_string(),
431                    ))
432                    .await?;
433                    txn.execute(Statement::from_sql_and_values(
434                        sea_orm::DatabaseBackend::Sqlite,
435                        "INSERT INTO tx_items (name) VALUES (?1)",
436                        [name.into()],
437                    ))
438                    .await?;
439                    Ok(())
440                })
441            })
442            .await
443            .unwrap();
444        }
445
446        let conn = db.connection().await.unwrap();
447        let row = conn
448            .query_one(Statement::from_string(
449                sea_orm::DatabaseBackend::Sqlite,
450                "SELECT COUNT(*) FROM tx_items".to_string(),
451            ))
452            .await
453            .unwrap()
454            .unwrap();
455        let count: i64 = row.try_get_by_index(0).unwrap();
456        assert_eq!(count, 2, "two sequential transactions should both commit");
457    }
458}