Muyinda Rogers
Muyinda Rogers

Reputation: 157

Scala Slick Class Table Definition, Error Declaring DateTime columns

Below is the DB Class I have compilation errors on Datetime columns when making table definitions.

  1. Created_on should be on update currrent date

  2. updated_on should just emulate the passed on date.

    package tables

     import play.data.format.Formats.DateTime
     import slick.driver.PostgresDriver.api._
    
    
     object Main {
    
        case class Account(
                       id: Long = 0L,
                       owner: Long,
                       name: String,
                       created_on: DateTime,
                       updated_on: DateTime,
                       author_id: Long,
                       updated_by: Long,
                       external_id: String
    
                     )
    

    class AccountTable(tag: Tag) extends TableAccount {

    def id  = column[Long]("id")
     def owner= column[Long]("id")
     def name= column[String]("name")
     def created_on= column[DateTime]("created_on")
     def updated_on= column[DateTime]("updated_on")
     def author_id= column[Long]("author_id")
     def updated_by= column[Long]("updated_by")
     def external_id= column[String]("external_id")
    
    
     def * = (owner, name, created_on, 
       updated_on,author_id,updated_by,external_id) <> (Account.tupled, 
       Account.unapply)
    

    }

    }

Upvotes: 0

Views: 122

Answers (1)

Richard Dallaway
Richard Dallaway

Reputation: 4320

I'm not sure what DateTime class you're using. Perhaps the Joda-time DateTime class?

For this, you need to provide a mapping from DateTime to a type the Slick knows about (and one that makes sense for the column in the database). For example, you could map DateTime to a Timestamp:

import java.sql.Timestamp
import org.joda.time.DateTime
import org.joda.time.DateTimeZone.UTC

// And in your `Main`...

implicit val jodaDateTimeType =
    MappedColumnType.base[DateTime, Timestamp](
      dt => new Timestamp(dt.getMillis),
      ts => new DateTime(ts.getTime, UTC)
    )

...for example. This is teaching Slick how to convert from DateTime to a type it knows about (Timestamp).

There's a tutorial on this that goes into more details in Chapter 5 of Essential Slick.

Since Slick 3.3, there's built-in support for many of the standard Java time formats, described in the release notes.

Also, since Slick 3 you can map classes using .mapTo for most cases. It's much nicer to read than <>:

def * = (
  owner, name, created_on, updated_on, author_id, updated_by, external_id
).mapTo[Account]

Upvotes: 1

Related Questions