Keyboard shortcuts

Press โ† or โ†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Adding Timestamps

We want to know when tasks were created and when they were last modified.

Add the Fields

use chrono::{DateTime, Utc};
use uuid::Uuid;

#[derive(Clone, Debug, DeriveEntityModel, EntityToModels)]
#[crudcrate(generate_router)]
#[sea_orm(table_name = "tasks")]
pub struct Model {
    #[sea_orm(primary_key, auto_increment = false)]
    #[crudcrate(primary_key, exclude(create, update), on_create = Uuid::new_v4())]
    pub id: Uuid,

    pub title: String,

    #[crudcrate(exclude(create, update), on_create = chrono::Utc::now())]
    pub created_at: DateTime<Utc>,

    #[crudcrate(exclude(create, update), on_create = chrono::Utc::now(), on_update = chrono::Utc::now())]
    pub updated_at: DateTime<Utc>,
}

Add chrono to Cargo.toml:

chrono = { version = "0.4", features = ["serde"] }

Update your table:

CREATE TABLE tasks (
    id TEXT PRIMARY KEY,
    title TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
)

Whatโ€™s Happening

๐Ÿ“‹ See test ๐Ÿ“‹ See test

Fieldon_createon_updateBehavior
created_atUtc::now()-Set once when created
updated_atUtc::now()Utc::now()Set on create, updated on every change

Both are exclude(create, update) so users canโ€™t manually set them.

Try It

# Create
curl -X POST http://localhost:3000/tasks \
  -H "Content-Type: application/json" \
  -d '{"title": "Learn timestamps"}'

Response:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "title": "Learn timestamps",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
# Update (wait a few seconds first)
curl -X PUT http://localhost:3000/tasks/550e8400-e29b-41d4-a716-446655440000 \
  -H "Content-Type: application/json" \
  -d '{"title": "Master timestamps"}'

Response - notice updated_at changed:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "title": "Master timestamps",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:45Z"
}

Our Task Model Now

pub struct Model {
    #[crudcrate(primary_key, exclude(create, update), on_create = Uuid::new_v4())]
    pub id: Uuid,

    pub title: String,

    #[crudcrate(exclude(create, update), on_create = chrono::Utc::now())]
    pub created_at: DateTime<Utc>,

    #[crudcrate(exclude(create, update), on_create = chrono::Utc::now(), on_update = chrono::Utc::now())]
    pub updated_at: DateTime<Utc>,
}

Now we have proper task tracking. But as we add more tasks, how do we find specific ones?

Next: Finding tasks - filter by field values.