Skip to content

Instantly share code, notes, and snippets.

@hendi
Last active September 7, 2024 20:02
Show Gist options
  • Select an option

  • Save hendi/3ff7f988a51125d757095d5fd2a8c216 to your computer and use it in GitHub Desktop.

Select an option

Save hendi/3ff7f988a51125d757095d5fd2a8c216 to your computer and use it in GitHub Desktop.
Rust: rocket with sqlx
#[macro_use] extern crate rocket;
use std::env;
use anyhow::Result;
use rocket::State;
use rocket::http::Status;
use sqlx::{Pool, Postgres};
use sqlx::postgres::PgPoolOptions;
#[derive(Debug)]
pub struct User {
pub id: i32,
pub name: String,
}
impl User {
pub async fn find_by_id(id: i32, pool: &Pool<Postgres>) -> Result<User> {
let user = sqlx::query_as!(User, "SELECT * FROM my_table WHERE id = $1", id)
.fetch_one(&*pool)
.await?;
Ok(user)
}
}
#[get("/<id>")]
async fn hello(pool: State<'_, Pool<Postgres>>, id: i32) -> Result<String, Status> {
let user = User::find_by_id(id, &pool).await;
match user {
Ok(user) => Ok(format!("Hello {}!", &user.name)),
_ => Err(Status::NotFound)
}
}
#[rocket::main]
async fn main() -> Result<()> {
let database_url = env::var("DATABASE_URL")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await?;
rocket::ignite()
.mount("/", routes![hello])
.manage(pool)
.launch()
.await?;
Ok(())
}
@hendi
Copy link
Copy Markdown
Author

hendi commented Dec 22, 2020

CREATE TABLE public.my_table (
	id int4 NOT NULL,
	"name" varchar NOT NULL
);

@StaticVoidMoon
Copy link
Copy Markdown

Hi. just want to say thank you very for this snippet.

@hendi
Copy link
Copy Markdown
Author

hendi commented Oct 12, 2021

Hi. just want to say thank you very for this snippet.

Thank you for your comment, it really made my day :-) Be sure to check out the rocket channel on matrix as well, many friendly and helpful people hang out there!

@gangov
Copy link
Copy Markdown

gangov commented Dec 14, 2021

hey, what did you set in the cargo.toml file for sqlx? I mean what runtime feature did you choose?

@hendi
Copy link
Copy Markdown
Author

hendi commented Dec 20, 2021

Not sure what I was using back then, but currently my Cargo.toml contains this:

sqlx = { version = "0.5.1", features = [ "runtime-tokio-rustls", "postgres", "chrono", "macros", "migrate", "uuid", "json" ] }

@nvima
Copy link
Copy Markdown

nvima commented Jan 29, 2022

May I ask why you took i32 and not u32?

@hendi
Copy link
Copy Markdown
Author

hendi commented Jan 31, 2022

Just lazyness, I'd use a uuid in practice. Bit you're right, even in this example u32 would be preferable to i32.

@aburd
Copy link
Copy Markdown

aburd commented Feb 5, 2022

Many thanks for this gist πŸ™‡

@3nt3
Copy link
Copy Markdown

3nt3 commented May 27, 2022

What version of rocket does this use?

@3nt3
Copy link
Copy Markdown

3nt3 commented May 27, 2022

Line 30 doesn't compile unless I change it to &State<Pool<Postgres>>

@opeolluwa
Copy link
Copy Markdown

opeolluwa commented Jul 8, 2022

Hi there 😊
This just saved my day. Where do I add create table if not exists.

@reidaruss
Copy link
Copy Markdown

Line 30 doesn't compile unless I change it to &State<Pool<Postgres>>

Been trying to figure out what to change this to for a while, this worked thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment