Search code examples
scalasorm

How to include timestamp(created_at and updated_at) on my models using SORM?


ActiveRecord handle timestamps doing something like this:

  • Inserting data? created_at is defined
  • Updating data? updated_at is redefined

How would I do it using SORM?


Solution

  • At a first glance something like this could work:

    import org.joda.time._
    object Db extends Instance (entities = ...) {
      override def save [T <: AnyRef : TypeTag] ( v : T ) 
        = v match {
            case v : Artist with Persisted =>
              super.save( v.copy( updatedAt = DateTime.now() ) )
            case v : Artist =>
              super.save( v.copy( createdAt = DateTime.now() ) )
            // ... so on for other entities
            case v =>
              super.save(v)
          }
    }
    

    But then how would you create those artist instances from scratch? Should those date fields be assigned with messy nulls or null-ish date values or should they maybe get wrapped in Options? Well, either of those should solve the problem, but here is another option:

    import org.joda.time._
    case class Artist 
      ( name : String, 
        updatedAt : DateTime = DateTime.now(),
        createdAt : DateTime = DateTime.now() )
    
    object Db extends Instance (entities = ...) {
      override def save [T <: AnyRef : TypeTag] ( v : T ) 
        = v match {
            case v : Artist with Persisted =>
              super.save( v.copy( updatedAt = DateTime.now() ) )
            case v =>
              super.save(v)
          }
    }
    

    I gotta tell you the whole problem doesn't feel very natural to me. I can't imagine scenarios where that kinda behaviour would be benefitial. But then again I've presented you the options.