Is there any Sqlx with Rocket tutorial?

Hi,
Hobby coder here(I'm an IT architect as a day job, so please bear with me :stuck_out_tongue: )

Now that Rocket 0.5 is in RC I am getting back to my Rust learning path and trying to port a gym web app I made in python(django) years ago. I'd like to use sqlx for the db connection and I am looking(without success) at some tutorial on how to integrate the 2 of them(I can't make head over heels of API docs... so I need tutorials)

Anyone has seen anything for that?

Thanks

The repo isn't public yet unfortunately, but that's what I'm using for a project of mine. That said, it's pretty simple. First make your pool and add it to the server's state with manage

    let database_url = "postgresql://...";
    let pool = sqlx::PgPool::connect(database_url)
        .await
        .expect("Failed to connect to database");
    rocket::build()
         // I added the type annotation below just for my own assurance, since the type is used to access it later
        .manage::<PgPool>(pool)
        // and so on...

Having done this, you can access the database from any of your routes by adding it as an argument

#[get("/")]
async fn index(pool: &rocket::State<PgPool>) -> &'static str {
    sqlx::query!("SELECT * FROM some_table")
        .fetch_all(pool.inner())
        .await
    // ...
}
3 Likes

Well, not particularly for Rocket but in the Zero to production in Rust book, the author uses Actix-web with Sqlx:

Thanks for the snippet reference. I now have the basic connectivity in place :slight_smile:

Thanks also for the book reference. I already have the Manning book " Rust Servers, Services, and Apps(MEAP version)" which uses Actix and SQLx that I follow along and try to "port" to Rocket(Rocket API is much closer than actix to what I'm used with Django.) I have read the sample of the book you linked and I think I will acquire it too, I see alot of topics in the TOC that should help me, even though it's also with actix.

I can't wait for the first book that will cover Rocket. The count of books that basically said: "we went with framework Actix/Warp, because Rocket isn't async yet" :frowning: is up to 3 now. (The linked book from moy210, the one I mentionned earlier, and also the newest MEAP from Manning, "Rust Web Development")

Wow, surprised how simple it is. This post really helped me, as I could not find this documented anywhere else either. Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.