From c2b03b37b55d6020cf6c00c8b2e8677dca4190e9 Mon Sep 17 00:00:00 2001 From: Gabriel Kaszewski Date: Fri, 2 Jan 2026 05:40:34 +0100 Subject: [PATCH] Refactor database connection handling and configuration --- src/db.rs | 69 +++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 15 deletions(-) diff --git a/src/db.rs b/src/db.rs index 87bf7b6..a1ae176 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,21 +1,60 @@ +use std::time::Duration; use sqlx::{Pool, Sqlite}; -#[cfg(feature = "db-sqlx")] -pub async fn connect_sqlite(url: &str) -> Result, sqlx::Error> { - sqlx::sqlite::SqlitePoolOptions::new() - .max_connections(5) - .connect(url) - .await -} - -// Future expansion for Postgres #[cfg(feature = "postgres")] use sqlx::Postgres; -#[cfg(feature = "postgres")] -pub async fn connect_postgres(url: &str) -> Result, sqlx::Error> { - sqlx::postgres::PgPoolOptions::new() - .max_connections(5) - .connect(url) - .await +/// Universal Database Configuration +#[derive(Debug, Clone)] +pub struct DatabaseConfig { + pub url: String, + pub max_connections: u32, + pub acquire_timeout: Duration, } + +impl Default for DatabaseConfig { + fn default() -> Self { + Self { + url: "sqlite::memory:".to_string(), + max_connections: 5, + acquire_timeout: Duration::from_secs(30), + } + } +} + +/// A wrapper around various DB pools. +/// The Template uses this type so it doesn't care if it's Sqlite or Postgres. +#[derive(Clone, Debug)] +pub enum DatabasePool { + Sqlite(Pool), + #[cfg(feature = "postgres")] + Postgres(Pool), +} + +/// The single entry point for connecting to any DB. +pub async fn connect(config: &DatabaseConfig) -> Result { + // 1. Try Postgres if the feature is enabled AND the URL looks like postgres + #[cfg(feature = "postgres")] + if config.url.starts_with("postgres://") || config.url.starts_with("postgresql://") { + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(config.max_connections) + .acquire_timeout(config.acquire_timeout) + .connect(&config.url) + .await?; + return Ok(DatabasePool::Postgres(pool)); + } + + // 2. Default to Sqlite + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(config.max_connections) + .acquire_timeout(config.acquire_timeout) + .connect(&config.url) + .await?; + + Ok(DatabasePool::Sqlite(pool)) +} + +// Re-export specific connectors if you still need manual control +pub async fn connect_sqlite(url: &str) -> Result, sqlx::Error> { + sqlx::sqlite::SqlitePoolOptions::new().connect(url).await +} \ No newline at end of file