modo/db/managed.rs
1use crate::error::Result;
2use crate::runtime::Task;
3
4use super::database::Database;
5
6/// Wrapper for graceful shutdown integration with [`crate::run!`].
7///
8/// Wraps a [`Database`] so it can be registered as a [`Task`] with the
9/// modo runtime. On shutdown the inner `Database` is dropped, which
10/// releases the underlying libsql connection and database handle once the
11/// last clone is gone.
12///
13/// Created by [`managed`].
14pub struct ManagedDatabase(Database);
15
16impl Task for ManagedDatabase {
17 async fn shutdown(self) -> Result<()> {
18 // Dropping Database drops the Arc. When the last reference is dropped,
19 // Inner is dropped, which drops libsql::Connection and libsql::Database.
20 // libsql handles cleanup internally.
21 drop(self.0);
22 Ok(())
23 }
24}
25
26/// Wrap a [`Database`] for use with [`crate::run!`].
27///
28/// # Examples
29///
30/// ```rust,no_run
31/// use modo::db;
32///
33/// # async fn example() -> modo::Result<()> {
34/// let config = db::Config::default();
35/// let db = db::connect(&config).await?;
36/// let task = db::managed(db.clone());
37/// // Register `task` with modo::run!() for graceful shutdown
38/// # Ok(())
39/// # }
40/// ```
41pub fn managed(db: Database) -> ManagedDatabase {
42 ManagedDatabase(db)
43}