rustrust-diesel

How to insert a SQL literal call to "NOW()" with diesel?


if I have a schema (psql) using fields TIMESTAMP (not tz, assume UTC for all times)

in rust i can represent them with

// schema.rs
diesel::table! {
    mytable (id) {
        id -> Int4,
        event_date -> Timestamp,
        ...
// models.rs
#[derive(Queryable, Selectable, Insertable)]
#[diesel(table_name = crate::database::schema::mytable)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct MyTable {
    pub id: i32,
    pub event_date: chrono::NaiveDateTime,
    ...

How can I insert/update a record, in a way that the resulting query will have a call to SQL's NOW(), such as: event_date=NOW()?


Solution

  • You obviously can't use your existing model to have the database insert the timestamp, it always includes a fixed and predetermined 1 chrono::NaiveDateTime.

    You can either

    diesel::dsl::now is in no way compatible with any dateTime type that I can use on a diesel model

    I think you missed that diesel::dsl::now is a datetime type which you can use in a diesel model. It is trivially compatible with itself.


    1determined when you create the query in your program