How to get 'Char' values from Postgres with Anorm
Asked Answered
E

2

2

I have a postgres table -

CREATE TABLE "Contest"
(
  id serial NOT NULL,
  name varchar(100) NOT NULL,
  type char(1) NOT NULL,
  status char(1) NOT NULL,
  ...
)

I'm trying to get field values type and status back to my Play 2.x (Anorm) application:

 val parseContest = {
  get[Pk[Int]]("id") ~
  get[String]("name") ~
  get[Char]("type") ~
  get[Char]("status") map {
  case id~name~c_type~status =>
    Contest(id, name, c_type, status)
  }
}

and get error:

could not find implicit value for parameter extractor: anorm.Column[Char]

Looks like 'Char' is not supported by anorm. What should I change in my code? Is it good practice to use get[String]("status") and then status.head as workaround?

Earleanearleen answered 16/11, 2013 at 21:52 Comment(0)
G
1

I think you could write an implicit converter for your char columns. That would look like this:

implicit def columnToChar: Column[Char] = {
    Column[Char](transformer = {
      (value, meta) =>
        val MetaDataItem(qualified, nullable, clazz) = meta
        value match {
          case ch: String => Right(ch.head)
          case _ => Left(TypeDoesNotMatch("Cannot convert " + value + " to Char for column " + qualified))
        }
    })
  }

Then be sure this converter is in scope.

I'm not sure the value would be a String but you can check it and make the corresponding corrections.

Gamopetalous answered 20/11, 2013 at 8:41 Comment(0)
P
1

There is recently merged PR on Anorm about that: https://github.com/playframework/playframework/pull/2189

Periapt answered 20/12, 2013 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.