Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To declare a datetime field in SQLx Rust, you can use the chrono library to create a custom DateTime type that can be mapped to the database column.

  1. Add the chrono and sqlx libraries to your project:
[dependencies]
chrono = { version = "0.4", features = ["serde"] }
sqlx = { version = "0.3", default-features = false, features = ["chrono"] }
  1. Create a custom DateTime type using chrono:
use chrono::{DateTime, Utc};

#[derive(sqlx::Type, Debug)]
#[sqlx(transparent)]
pub struct MyDateTime(DateTime<Utc>);
  1. Use the custom DateTime type in your SQLx Rust queries:
#[derive(sqlx::FromRow, Debug)]
struct MyType {
    id: i32,
    name: String,
    created_at: MyDateTime,
}

let my_type = sqlx::query_as!(
    MyType,
    "SELECT id, name, created_at FROM my_table WHERE id = $1",
    my_id
)
.fetch_one(&pool)
.await?;

The MyDateTime type will automatically serialize and deserialize the datetime values in the database.