dioxus icon indicating copy to clipboard operation
dioxus copied to clipboard

cannot connect to db(Sea ORM)

Open DeadPoetSpoon opened this issue 1 year ago • 2 comments

Problem

using Sea ORM Database::connect in Lazy

when call in server_fn will block on connect without errors

direct call in server_fn Database::connect is fine

Steps To Reproduce

Steps to reproduce the behavior:

  • set up sea orm
  • in main.rs
#[cfg(feature = "server")]
static APPSTATE: Lazy<AppServerState> = Lazy::new(|| async move {
    use migration::{Migrator, MigratorTrait};
    let db =
            Database::connect("postgres://spoon:mahjong_at_home@localhost:5432/mahjong_at_home")
                .await
                .expect("Failed to connect to database");
    Migrator::up(&db, None)
            .await
            .expect("Failed to migrator up");
    dioxus::Ok(AppServerState { db })
});
  • in server_fn
user.insert(&crate::APPSTATE.db)
        .await
        .map_err(|err| ServerFnError::ServerError {
            message: format!("DB Error {err:?}"),
            code: 500u16,
            details: None,
        })?;

Expected behavior

server state with a db connection can be used in any server_fn

Screenshots

Environment:

  • Dioxus version: main
  • Rust version: 1.89
  • OS info: manjaro
  • App platform: server

Questionnaire

I'm interested in fixing this myself but don't know where to start.

DeadPoetSpoon avatar Oct 19 '25 00:10 DeadPoetSpoon

switch to dioxus: v0.6.3, and use std::sync::LazyLock with a init_server work fine.

APPSTATE type: LazyLock<Arc<RwLock<AppServerState>>>

use dioxus::prelude::*;
#[cfg(feature = "server")]
use {
    sea_orm::{Database, DatabaseConnection},
    std::sync::{Arc, LazyLock},
    tokio::sync::RwLock,
};

#[cfg(feature = "server")]
#[derive(Clone, Debug, Default)]
pub struct AppServerState {
    db: DatabaseConnection,
}

#[cfg(feature = "server")]
pub static APPSTATE: LazyLock<Arc<RwLock<AppServerState>>> =
    LazyLock::new(|| Arc::new(RwLock::new(AppServerState::default())));

#[server]
pub async fn init_server() -> Result<(), ServerFnError> {
    use dioxus::logger::tracing;
    use migration::{Migrator, MigratorTrait};
    let state = Arc::clone(&APPSTATE);
    let mut state = state.write().await;
    let db = Database::connect("postgres://spoon:mahjong_at_home@localhost:5432/mahjong_at_home")
        .await?;
    tracing::debug!("DONE: connect to db");
    Migrator::up(&db, None).await?;
    tracing::debug!("DONE: migrator up");
    state.db = db;
    drop(state);
    Ok(())
}

Connect DB in Lazy async init func may block tokio::runtime? I will test on dioxus: v0.7 after released.

DeadPoetSpoon avatar Oct 25 '25 02:10 DeadPoetSpoon

This was an issue with Lazy<T> that is now fixed!

jkelleyrtp avatar Nov 11 '25 19:11 jkelleyrtp