Ask Your Question
1

What is the process of declaring a datetime field in sqlx rust?

asked 2021-11-25 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-12-27 18:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-25 11:00:00 +0000

Seen: 12 times

Last updated: Dec 27 '22