Permalink
Browse files

Merge pull request #2434 from cchantep/anorm-datecol-specs

Specifications for date column
  • Loading branch information...
2 parents 73d0dc6 + 575f667 commit 7d0d75a435e4127c8cdf849883e1f01ec9929f46 @jroper jroper committed Mar 5, 2014
@@ -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"))
}
}
@@ -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._
@@ -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 }))

0 comments on commit 7d0d75a

Please sign in to comment.