#init function

14 messages · Page 1 of 1 (latest)

rich kite
#

hey um is there a way to run a function before tauri start?
i tried something like this but not working

pub static DB: Surreal<Db> = Surreal::init();

pub async fn init() -> Result<(), Box<dyn Error>> {
    DB.connect::<RocksDb>("temp.db").await?;

    DB.use_ns("test")
      .use_db("test")
      .await?;
    Ok(())
}
 
 fn main() {
init();    
tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet,alpha])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

exotic sonnet
# rich kite hey um is there a way to run a function before tauri start? i tried something li...

the builder has a .setup method, try calling it in there. ex: ```rust
pub static DB: Surreal<Db> = Surreal::init();

pub async fn init_db() -> Result<(), Box<dyn Error>> {
DB.connect::<RocksDb>("temp.db").await?;

DB.use_ns("test")
.use_db("test")
.await?;
Ok(())
}

fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet,alpha])
.setup(| app | {
init_db();
Ok(());
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

rich kite
# exotic sonnet the builder has a `.setup` method, try calling it in there. ex: ```rust pub stat...

i tried that too

but when i call it in command function i got this error

thread 'tokio-runtime-worker' panicked at 'called Result::unwrap() on an Err value: Api(ConnectionUninitialised)

 fn main() {
    tauri::Builder::default()
        .setup(|app| {
            init_db();
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![greet,alpha])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[tauri::command]
async fn alpha(name: String) -> Vec<Person> {
    // let db = Surreal::new::<RocksDb>("temp.db").await?;
    // db.use_ns("test").use_db("test").await?;
   
    // init_db().await;
    let created = DB
    .query("INSERT INTO greeting {
        value: $value
    };")
    .bind(("value", name))
    .await;

    let mut groups: Vec<Person>  = DB.query("SELECT value FROM greeting").await.unwrap().take(0).unwrap();
  

    return groups;
}
#

if i call init_db() inside alpha function it work just fine
but im not sure if thats the correct way to do it

exotic sonnet
rich kite
#

Well thats possible, i will try again later

I need sleep PepeHands

balmy creek
#

Maybe try not storing your db connection like that. Instead use Tauri's State. As an example, here's how I connect to a local sqlite db in a tauri app, and then fetch that connection pool later on in a tauri command (a bit of sqlx fluff around it but I hope I still get the point across):

struct DbCon {
    db: Mutex<Option<SqlitePool>>,
}

#[tauri::command]
async fn foo(con: State<'_, DbCon>) -> Result<Bar> {
  let mutex = con.db.lock().await;
  let pool = mutex.as_ref().ok_or(Error::DatabaseNotLoaded)?;
  
  sqlx::query_as!(Bar, "SELECT * FROM bar")
    .fetch_one(pool)
    .await
    .map_err(Error::Sql)
}

pub fn init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("sql")
  .setup(|app| {
    // ...
    tauri::async_runtime::block_on(async {
      let pool = SqlitePool::connect(&db_path).await?;
      app.manage(DbCon { db: Mutex::new(Some(pool))};
      Result::<()>::Ok(())
    })?;
  })
  // ...
  .build()
}
#

(the init function looks a bit differently as I am doing it in a Tauri plugin instead of the main application, but the same logic applies)

rich kite
exotic sonnet
rich kite
#

or add settimeout 1s

#

maybe if i have a way to check if the connection is ready i can improve it