Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a datetime field in sqlx rust

Tags:

rust

I have a struct as follows?

pub struct Instrument {
  pub id:i32,
  pub expiry_on: <this should be a date field>
}

What should I give the type of expiry_on. I want to use the struct inside sqlx::query_as!() to fetch records from postgres ?

expiry_on is a timestampz Postgres field.

like image 537
Asnim P Ansari Avatar asked May 02 '20 14:05

Asnim P Ansari


1 Answers

Under the assumption that your expiry_on field in postgres is a timestamptz: Depending on the time library you use, you will either want to add the chrono feature or the time feature to sqlx. Which you can do in Cargo.toml like this:

[dependencies]
sqlx = { version = "*", features = [ "chrono" ] }

or

sqlx = { version = "*", features = [ "time" ] }

instead of

sqlx = "*"

Where * is whatever version you're using.

You then change the following in Instrument (assuming chrono):

pub struct Instrument {
    pub id: i32,
    pub expiry_on: chrono::DateTime<chrono::Utc>,
}
like image 128
izik1 Avatar answered Nov 18 '22 08:11

izik1