sfackler / rust-postgres

Native PostgreSQL driver for the Rust programming language
Apache License 2.0
3.44k stars 436 forks source link

retrieving postgres `date` type without chrono #947

Closed djanatyn closed 2 years ago

djanatyn commented 2 years ago

Today while pair-programming, we had a postgres database with a date column. We were trying to use postgres::row::Row#get with postgres::types::Date:

/// A wrapper that can be used to represent infinity with `Type::Date` types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Date<T> {
    /// Represents `infinity`, a date that is later than all other dates.
    PosInfinity,
    /// Represents `-infinity`, a date that is earlier than all other dates.
    NegInfinity,
    /// The wrapped date.
    Value(T),
}

At first we were confused by what T should be, and tried i32:

let a: postgres::types::Date<i32> = row.get("date");

That didn't end up working (sorry, don't have the error message), so we switched to using the with-chrono-0_4 feature, and returned chrono::NaiveDate instead:

let date: chrono::NaiveDate = row.get("date");

I was wondering:

Thank you for your time!

sfackler commented 2 years ago

postgres::types::Date<chrono::NaiveDate>.

The date enum handles the infinity values that Postgres supports but Rust date types typically do not. If you aren't using infinite date values in your database you should just use chrono::NaiveDate directly.

djanatyn commented 2 years ago

Thank you, that explains it!