Skip to content

SQLite: datetime and timestamp can't query as chrono::DateTime<chrono::Utc>? #598

Description

@biluohc

Version: v0.4.0-beta.1 and master

Problem: Whether it is datetime or timestamp in sql, the rust code can choose NaiveDatetime only.

create table users (
    id INTEGER primary key AUTOINCREMENT not null,
    name text UNIQUE not null,
    email char(20) UNIQUE not null,
    pass char(65) not null, -- 'passwd hash'
    create_dt datetime not null default (datetime('now')), -- 'create datetime'
    update_dt datetime not null default (datetime('now')) -- 'update datetime'
);

code
```rust
#[cfg(any(feature = "postgres", feature = "sqlite"))]
type SqlID = i64;

// time_zone: https://github.com/launchbadge/sqlx/issues/329
#[cfg(any(feature = "mysql", feature = "postgres"))]
type SqlDateTime = chrono::DateTime<chrono::Utc>;
// type SqlDateTime = chrono::NaiveDateTime;

// Extend derive(FromRow): https://github.com/launchbadge/sqlx/issues/156
#[cfg(any(feature = "sqlite"))]
type SqlDateTime = chrono::DateTime<chrono::Utc>;

#[derive(FromRow, Serialize, Deserialize, Debug)]
pub struct User {
    pub id: SqlID,
    pub name: String,
    // pub phone: String,
    pub email: String,
    // not return password
    #[serde(skip_serializing)]
    pub pass: String,
    pub create_dt: SqlDateTime,
    pub update_dt: SqlDateTime,
}

    async fn user_query(&self, name: &str) -> sqlx::Result<User> {
        sqlx::query_as!(
            User,
            r#"
        SELECT id, name, email, pass, create_dt, update_dt
        FROM users
        where name = ?
                "#,
            name
        )
        .fetch_one(&self.sql)
        .await
    }

Error:

error[E0308]: mismatched types
  --> src/users/dao.rs:32:9
   |
32 | /         sqlx::query_as!(
33 | |             User,
34 | |             r#"
35 | |         SELECT id, name, email, pass, create_dt, update_dt
...  |
39 | |             name
40 | |         )
   | |_________^ expected struct `chrono::DateTime`, found struct `chrono::NaiveDateTime`
   |
   = note: expected struct `chrono::DateTime<chrono::Utc>`
              found struct `chrono::NaiveDateTime`
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions