3

I have a custom time type because time's authors doesn't want to add a Default value yet:

#[derive(Debug, Clone, Copy)]
pub struct OffsetDateTime(pub time::OffsetDateTime);

impl OffsetDateTime {
    pub fn now_utc() -> Self {
        Self(time::OffsetDateTime::now_utc())
    }
}

impl Default for OffsetDateTime {
    fn default() -> Self {
        Self(time::OffsetDateTime::UNIX_EPOCH)
    }
}

impl From<time::OffsetDateTime> for OffsetDateTime {
    fn from(o: time::OffsetDateTime) -> Self {
        Self(o)
    }
}

impl From<OffsetDateTime> for time::OffsetDateTime {
    fn from(o: OffsetDateTime) -> Self {
        o.0
    }
}

If I use this simple sqlx code:

#[derive(Debug, Default, sqlx::FromRow)]
pub struct Player {
    pub id: String,
    pub created_at: OffsetDateTime,
    pub name: String,
}

let pla = sqlx::query_as!(
    Player,
    r#"SELECT * from player where id = $1"#,
    '1'
)
.fetch_one(&*self.pool)
.await?;

it errors with:

error[E0308]: mismatched types
   |
66 |           let pla = sqlx::query_as!(
   |  ___________________^
67 | |             Player,
68 | |             r#"SELECT * from player where id = $1"#,
70 | |             id
71 | |         )
   | |_________^ expected struct `custom::types::OffsetDateTime`, found struct `time::OffsetDateTime`
   |
   = note: struct `time::OffsetDateTime` and struct `custom::types::OffsetDateTime` have similar names, but are actually distinct types
note: struct `time::OffsetDateTime` is defined in crate `time`
  --> C:\Users\Fred\.cargo\registry\src\github.com-1ecc6299db9ec823\time-0.3.17\src\offset_date_time.rs:31:1
   |
31 | pub struct OffsetDateTime {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^
note: struct `custom::types::OffsetDateTime` is defined in crate `custom`
   |
4  | pub struct OffsetDateTime(pub time::OffsetDateTime);
   | ^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: this error originates in the macro `$crate::sqlx_macros::expand_query` which comes from the expansion of the macro `sqlx::query_as` (in Nightly builds, run with -Z macro-backtrace for more info)
help: try wrapping the expression in `custom::types::OffsetDateTime`
  --> C:\Users\Fred\.cargo\registry\src\github.com-1ecc6299db9ec823\sqlx-0.6.2\src\macros\mod.rs:561:9
   |
561|         custom::types::OffsetDateTime($crate::sqlx_macros::expand_query!(record = $out_struct, source = $query, args = [$($args)*]))
   |         ++++++++++++++++++++++++++++++                                                                                             +

How can I fix this?

Should I instruct sqlx to handle my custom OffsetDateTime? How?

Yuri Astrakhan
  • 8,808
  • 6
  • 63
  • 97
Fred Hors
  • 3,258
  • 3
  • 25
  • 71

1 Answers1

0

From the docs on query_as:

The field types must be the Rust equivalent of their SQL counterparts

Means you have to use the types in the type map corresponding to your db (example for postgres).

Or in other words, you can't use custom types with query_as

cafce25
  • 15,907
  • 4
  • 25
  • 31