feat: add database connection pooling
This commit is contained in:
parent
e834b3308a
commit
303e3ffd4e
4 changed files with 34 additions and 7 deletions
|
|
@ -16,7 +16,7 @@ pub async fn register(
|
|||
};
|
||||
|
||||
{
|
||||
let mut conn = ctx.data().conn.lock().unwrap();
|
||||
let mut conn = ctx.data().pool.get()?;
|
||||
user_insert(&mut conn, &user);
|
||||
}
|
||||
|
||||
|
|
@ -26,7 +26,7 @@ pub async fn register(
|
|||
#[poise::command(prefix_command, slash_command)]
|
||||
pub async fn registered(ctx: Context<'_>) -> Result<(), Error> {
|
||||
let users = {
|
||||
let mut conn = ctx.data().conn.lock().unwrap();
|
||||
let mut conn = ctx.data().pool.get()?;
|
||||
user_all(&mut conn)
|
||||
};
|
||||
|
||||
|
|
|
|||
14
src/main.rs
14
src/main.rs
|
|
@ -6,6 +6,8 @@ use diesel::Connection;
|
|||
use poise::serenity_prelude as serenity;
|
||||
use std::sync::Mutex;
|
||||
use std::{env::var, time::Duration};
|
||||
use diesel::r2d2::{ConnectionManager, Pool};
|
||||
use diesel::sqlite::SqliteConnection;
|
||||
|
||||
// Types used by all command functions
|
||||
type Error = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
|
@ -14,7 +16,7 @@ type Context<'a> = poise::Context<'a, Data, Error>;
|
|||
// Custom user data passed to all command functions
|
||||
pub struct Data {
|
||||
client: AffluencesClient,
|
||||
conn: Mutex<diesel::sqlite::SqliteConnection>,
|
||||
pool: Pool<ConnectionManager<SqliteConnection>>
|
||||
}
|
||||
|
||||
async fn on_error(error: poise::FrameworkError<'_, Data, Error>) {
|
||||
|
|
@ -34,6 +36,12 @@ async fn on_error(error: poise::FrameworkError<'_, Data, Error>) {
|
|||
}
|
||||
}
|
||||
|
||||
fn db_connection_pool(url: &str) -> Pool<ConnectionManager<SqliteConnection>> {
|
||||
let manager = ConnectionManager::new(url);
|
||||
|
||||
Pool::builder().test_on_check_out(true).build(manager).expect("oops")
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// FrameworkOptions contains all of poise's configuration option in one struct
|
||||
|
|
@ -95,9 +103,7 @@ async fn main() {
|
|||
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
|
||||
Ok(Data {
|
||||
client: AffluencesClient::new(),
|
||||
conn: Mutex::new(
|
||||
diesel::sqlite::SqliteConnection::establish("affy.db").unwrap(),
|
||||
),
|
||||
pool: db_connection_pool("affy.db")
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue