Use Timestamps

This guide shows you how to use automatic timestamps for tracking when records are created and updated.

Add Timestamps to Schema

Use the timestamps helper in your table definition:

schema.table :posts do
  primary :id, Int64, auto_increment: true
  column :title, String
  timestamps  # Adds created_at and updated_at columns
end
schema.posts.create!

This creates two columns:

  • created_at - Set when record is first saved

  • updated_at - Updated each time record is saved

Add to Model

Define the timestamp properties in your model:

struct Post
  include CQL::ActiveRecord::Model(Int64)
  db_context MyDB, :posts

  property id : Int64?
  property title : String
  property created_at : Time?
  property updated_at : Time?

  def initialize(@title : String)
  end
end

Automatic Timestamps

CQL automatically sets timestamps when you save:

Manual Timestamps with Callbacks

If you need more control, use callbacks:

Query by Timestamp

Filter records by their timestamps:

Add Timestamps to Existing Table

Create a migration:

Useful Timestamp Methods

Add helper methods to your model:

Verify It Works

Last updated

Was this helpful?