Skip to content

Commit

Permalink
Specification for date column
Browse files Browse the repository at this point in the history
  • Loading branch information
cchantep committed Mar 4, 2014
1 parent 73d0dc6 commit 575f667
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
12 changes: 12 additions & 0 deletions framework/src/anorm/src/main/scala/anorm/Column.scala
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,22 @@ object Column {
nonNull((value, meta) =>
anyToBigDecimal(value, meta).map(BigDecimal(_)))

/**
* Parses column as Java Date.
* Time zone offset is the one of default JVM time zone
* (see [[java.util.TimeZone.getDefault]]).
*
* {{{
* import java.util.Date
*
* val d: Date = SQL("SELECT last_mod FROM tbl").as(scalar[Date].single)
* }}}
*/
implicit val columnToDate: Column[Date] = nonNull { (value, meta) =>
val MetaDataItem(qualified, nullable, clazz) = meta
value match {
case date: Date => Right(date)
case time: Long => Right(new Date(time))
case _ => Left(TypeDoesNotMatch("Cannot convert $value: ${value.asInstanceOf[AnyRef].getClass} to Date for column $qualified"))
}
}
Expand Down
39 changes: 38 additions & 1 deletion framework/src/anorm/src/test/scala/anorm/ColumnSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,20 @@ package anorm
import javax.sql.rowset.serial.SerialClob

import acolyte.QueryResult
import acolyte.RowLists._
import acolyte.RowLists.{
bigDecimalList,
byteList,
dateList,
doubleList,
floatList,
intList,
stringList,
longList,
rowList1,
shortList,
timeList,
timestampList
}
import acolyte.Acolyte.{ connection, handleQuery }
import acolyte.Implicits._

Expand Down Expand Up @@ -248,6 +261,30 @@ object ColumnSpec extends org.specs2.mutable.Specification {
}
}

"Column mapped as date" should {
val time = System.currentTimeMillis

"be parsed from date" in withQueryResult(
dateList :+ new java.sql.Date(time)) { implicit con =>
SQL("SELECT d").as(scalar[java.util.Date].single).
aka("parsed date") must_== new java.util.Date(time)
}

"be parsed from timestamp" in withQueryResult(
timestampList :+ new java.sql.Timestamp(time)) { implicit con =>
SQL("SELECT ts").as(scalar[java.util.Date].single).
aka("parsed date") must beLike {
case d => d.getTime aka "time" must_== time
}
}

"be parsed from time" in withQueryResult(longList :+ time) { implicit con =>
SQL("SELECT time").as(scalar[java.util.Date].single).
aka("parsed date") must_== new java.util.Date(time)

}
}

def withQueryResult[A](r: QueryResult)(f: java.sql.Connection => A): A =
f(connection(handleQuery { _ => r }))

Expand Down

0 comments on commit 575f667

Please sign in to comment.