Run a plain SQL query in Diesel.rs


Sometimes I just need to get a single value out of the database, or in this case I wanted to include connectivity to the database in my liveness probe. Since I don’t need to load anything and just want to make sure the database is accessible I want to run a very simple query. Diesel is the ORM I’m using and it already has my database connectivity so to me it makes sense to use it to run my query. Here’s how to run an arbitrary SQL query in Diesel:

use diesel::result::Error;
use diesel::dsl::sql;
conn.run(|c| {
  let result: Result<i32, Error> = sql("SELECT 1").get_result(c);
  match result {
    Ok(one) => # Use the number 1
    Err(error) => # handle the error
  }
});

If you want to live dangerously you can skip the match on the Result and use .expect but I personally prefer to handle Results directly (or use ? to propagate the error).

And to give a more complete example; here is the liveness probe I’m using in my Rocket.rs app:

#[get("/liveness")]
async fn liveness(conn: MyDB) -> Status {
  conn.run(|c| {
    let result: Result<i32, Error> = sql("SELECT 1").get_result(c);
    match result {
      Ok(_) => Status::Ok,
      Err(_) => Status::ServiceUnavailable
    }
  }).await
}

In my case I don’t care what the value is but just whether the query actually returns. Now my application will check the connection to the database when Kubernetes runs its liveness check.

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *