Anorm parse float values
Asked Answered
F

1

12

In Play framework 2.0, I'm trying to load a real (i.e. single precision float) type column from PostgreSQL using a row parser like this:

case class Foo(bar: Float)

object Foo {
    def all = DB.withConnection { implicit c =>
        SQL("SELECT * FROM foo").as(fooParser *)
    }

    val fooParser = {
        get[Float]("bar") map {     
          case bar => Foo(bar)
        }
    }
}

This generates an error: could not find implicit value for parameter extractor: anorm.Column[Float]

When using double precision types everything works fine. Is it somehow possible to use single precision floats with Anorm?

Filomena answered 24/6, 2012 at 19:12 Comment(0)
R
13

You can always create your own column parser base on the existing ones:

 implicit def rowToFloat: Column[Float] = Column.nonNull { (value, meta) =>
  val MetaDataItem(qualified, nullable, clazz) = meta
  value match {
    case d: Float => Right(d)
    case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass + " to Float for column " + qualified))
  }
}

but it matches on the type of value returned by the JDBC driver which may not be correct (depends on the column definition).

Rogue answered 25/6, 2012 at 7:2 Comment(1)
check out the code here too: github.com/isaka/Play20/commit/…Lorca

© 2022 - 2024 — McMap. All rights reserved.