Rocket: How to use database macro (fairings) outside rocket

Created on 11 Aug 2019  路  3Comments  路  Source: SergioBenitez/Rocket

Hello, it is question, but not a bug

I have such db fairing and it works for routs:

#[database("my_db_name")]
pub struct RustyDbConn(MysqlConnection);

But I have one thread with rocket
and another thread with telegram bot

The question: How can I establish mysql connection from telegram bot thread?
Of course I am looking for reusing existing structs/code

I just haven't found answer in documentation. And was writing question here as maybe
it makes sense to add it in tutorials.

Forward thank you!

request

Most helpful comment

@timando great tip, thanks! This worked for me:

#[database("my_database")]
pub struct DBConn(mysql::Conn);

fn main() {
    let mut rocket = rocket::ignite().attach(DBConn::fairing());

    let DBConn(mut conn) = DBConn::get_one(&rocket).unwrap();
    tables::create_tables(&mut conn);
    drop(conn);

    rocket.launch()
}

All 3 comments

I don't think the current API makes this easy, and it might even be impossible if you only rely on what's publicly documented. The most "obvious"/readable thing today might be to extract the connection string from the configuration and create a second pool manually for the other thread.

I agree it would be useful to add functionality to get a second handle of sorts to the database pool, but I am not sure exactly what that API should look like.

The database pool will add a get_one associated function to the type, but you will need a reference to the Rocket instance. The only problem is getting a reference to the Rocket instance after it's launched.

@timando great tip, thanks! This worked for me:

#[database("my_database")]
pub struct DBConn(mysql::Conn);

fn main() {
    let mut rocket = rocket::ignite().attach(DBConn::fairing());

    let DBConn(mut conn) = DBConn::get_one(&rocket).unwrap();
    tables::create_tables(&mut conn);
    drop(conn);

    rocket.launch()
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

klnusbaum picture klnusbaum  路  4Comments

PSeitz picture PSeitz  路  3Comments

marcusball picture marcusball  路  3Comments

Qqwy picture Qqwy  路  3Comments

shssoichiro picture shssoichiro  路  4Comments