How to create an global database connection in Rust using SeaORM

192 Views Asked by At

I am quite new to Rust and I want to understand some concepts. How could I create a global connection here that I can further use in my services? This is my structure

/src
 /v3
  /routes/
  /config/
  /entities/
  /services/
 main.rs

And I would like to open the connection manually and be able to access it in services, for example, or where I will manipulate the database

use std::sync::Arc;

use axum::Router;
use once_cell::sync::Lazy;
use sea_orm::{Database, DatabaseConnection};
use tokio::net::TcpListener;
use crate::v3::config::env;

mod v3;

#[tokio::main]
async fn main() {
    // Init env
    env::init();

    let host: String = format!("0.0.0.0:{}", env::get_env("PORT"));

    let app: Router = v3::create_v3_router();

    let listener: TcpListener = tokio::net::TcpListener::bind(&host).await.unwrap();

    println!("Server running on {}", host);

    axum::serve(listener, app).await.unwrap();
}

mod.rs
pub fn create_v3_router() -> Router {
    Router::new()
        .merge(session_routes())
}

routes/session.rs
pub fn routes() -> Router {
    let router: Router = Router::new()
        .route("/api/v3/session", get(example_handler));

    return router
}


1

There are 1 best solutions below

0
On

See axum state.

db.rs

use sea_orm::ConnectOptions;
use sea_orm::DatabaseConnection;
use std::time::Duration;

use crate::other::env::API_ENV;

#[derive(Debug)]
pub struct DatabaseService {
    pub connection: DatabaseConnection,
}
impl DatabaseService {
    pub async fn init() -> Self {
        let mut connection_options = ConnectOptions::new(&API_ENV.db_url);
        connection_options
            .max_connections(100)
            .min_connections(5)
            .connect_timeout(Duration::from_secs(8))
            .acquire_timeout(Duration::from_secs(8))
            .idle_timeout(Duration::from_secs(8))
            .max_lifetime(Duration::from_secs(8))
            .sqlx_logging(false);

        // test connection
        #[allow(clippy::expect_used)]
        let connection = sea_orm::SqlxPostgresConnector::connect(connection_options)
            .await
            .expect("Can't connect to database");

        Self { connection }
    }
}

main.rs

let database_service = DatabaseService::init().await;

let app = Router::new()
    .route("/", get(handler))
    .with_state(database_service);

async fn handler(
    State(database_service): State<Arc<DatabaseService>>,
) {
    // and use `database_service.connection` to query data
}