Skip to content

Commit 5b5b528

Browse files
committed
feat: Database connections now automatically closed on program closing
1 parent 1fef66a commit 5b5b528

File tree

3 files changed

+31
-8
lines changed

3 files changed

+31
-8
lines changed

src/commands/run.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::{LUA, RUNTIME_FLAGS};
1+
use crate::{LUA, RUNTIME_FLAGS, components::database::DATABASE_POOLS};
22
use std::path::PathBuf;
33
use tracing::error;
44

@@ -94,6 +94,14 @@ pub async fn run_command(
9494
error!("{e}");
9595
}
9696

97+
let database_pools = DATABASE_POOLS.lock().await.clone();
98+
for i in database_pools {
99+
match i {
100+
crate::components::database::DatabaseType::Postgres(pool) => pool.close().await,
101+
crate::components::database::DatabaseType::Sqlite(pool) => pool.close().await,
102+
}
103+
}
104+
97105
std::process::exit(
98106
#[cfg(unix)]
99107
0,

src/components/database.rs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
use mlua::{LuaSerdeExt, UserData};
22
use sqlx::{Pool, Postgres, Row, Sqlite, migrate::MigrateDatabase};
3+
use std::sync::LazyLock;
4+
use tokio::sync::Mutex;
5+
6+
pub static DATABASE_POOLS: LazyLock<Mutex<Vec<DatabaseType>>> =
7+
LazyLock::new(|| Mutex::new(Vec::new()));
38

49
#[derive(Debug, Clone)]
510
pub enum DatabaseType {
@@ -39,9 +44,14 @@ impl Database {
3944
.connect(format!("sqlite:{url}").as_str())
4045
.await
4146
{
42-
Ok(pool) => Ok(Database {
43-
db: Some(DatabaseType::Sqlite(pool)),
44-
}),
47+
Ok(pool) => {
48+
let pool = DatabaseType::Sqlite(pool);
49+
50+
let mut database_pools = DATABASE_POOLS.lock().await;
51+
database_pools.push(pool.clone());
52+
53+
Ok(Database { db: Some(pool) })
54+
}
4555
Err(e) => Err(mlua::Error::runtime(format!(
4656
"Error connecting to Sqlite: {e:#?}"
4757
))),
@@ -52,9 +62,14 @@ impl Database {
5262
.connect(url.as_str())
5363
.await
5464
{
55-
Ok(pool) => Ok(Database {
56-
db: Some(DatabaseType::Postgres(pool)),
57-
}),
65+
Ok(pool) => {
66+
let pool = DatabaseType::Postgres(pool);
67+
68+
let mut database_pools = DATABASE_POOLS.lock().await;
69+
database_pools.push(pool.clone());
70+
71+
Ok(Database { db: Some(pool) })
72+
}
5873
Err(e) => Err(mlua::Error::runtime(format!(
5974
"Error connecting to Postgres: {e:#?}"
6075
))),

src/components/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use mlua::{ExternalError, LuaSerdeExt};
22

33
mod crypto;
4-
mod database;
4+
pub mod database;
55
mod datetime;
66
pub mod global;
77
pub mod http;

0 commit comments

Comments
 (0)