3

I have the following SQL table scheme

CREATE TABLE reservation (
    id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    timespan TSTZRANGE
);

INSERT INTO reservation(timespan) VALUES
    (TSTZRANGE(now() + INTERVAL '0 hour', now() + INTERVAL '1 hour')),
    (TSTZRANGE(now() + INTERVAL '2 hour', now() + INTERVAL '3 hour'));

and using rust-sqlx, I would like to retrieve those rows directly into a struct.

/*
[dependencies]
chrono = "0.4"
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.5", features = [ "runtime-tokio-native-tls" , "postgres" ] }
*/

use chrono::prelude::*;
use sqlx::FromRow;
use sqlx::postgres::{types::PgRange, PgPoolOptions};


#[derive(Debug, FromRow)]
struct Reservation {
    id: i32,
    timespan: PgRange<DateTime<Utc>>,
}

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let db_url: String = "postgresql://postgres:postgres@localhost/mydb".to_owned();

    let pool = PgPoolOptions::new()
        .max_connections(2)
        .connect(&db_url)
        .await?;

    let select_query = sqlx::query_as::<_, Reservation>("SELECT id, timespan FROM reservation");
    let reservations: Vec<Reservation> = select_query.fetch_all(&pool).await?;

    dbg!("{:?}", reservations);

    Ok(())
}

I am getting the following 2 following errors

error[E0277]: the trait bound `PgRange<chrono::DateTime<chrono::Utc>>: Type<_>` is not satisfied
...
...
error[E0277]: the trait bound `chrono::DateTime<chrono::Utc>: Type<Postgres>` is not satisfied

How do I go about manually implementing these trait bounds? or is there a simpler way to achieve the same thing?

1 Answer 1

2

Newbie mistake! I just had to add chrono flag for sqlx in Cargo.toml

sqlx = { version = "0.5", features = [ "runtime-tokio-native-tls" , "postgres" , "chrono" ] }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.