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.
chrono
and sqlx
libraries to your project:[dependencies]
chrono = { version = "0.4", features = ["serde"] }
sqlx = { version = "0.3", default-features = false, features = ["chrono"] }
DateTime
type using chrono
:use chrono::{DateTime, Utc};
#[derive(sqlx::Type, Debug)]
#[sqlx(transparent)]
pub struct MyDateTime(DateTime<Utc>);
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.
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
Asked: 2021-11-25 11:00:00 +0000
Seen: 12 times
Last updated: Dec 27 '22
How to set up Database First configuration in Entity Framework 7 for MVC 6?
What is a left join in Rust Diesel?
What is the issue with establishing a connection between Flyway and SSL-enabled PostgreSQL?
How to add new SQL Server records and modify existing records in pandas dataframe?
How to indicate the name of the database in EF Core?
What are the Cordapp Certificates used for in terms of signing and interacting?
How can SSL be used with CqlSessionFactoryBean in Springboot Cassandra?
How can I address the issue of Content Security Policy blocking more than I had anticipated?
How do I resolve a 502 error when attempting to call an HTTPS REST API from an HTTP REST API?