Come ottenere valori "Char" da Postgres con Anorm
-
21-12-2019 - |
Domanda
Ho un tavolo di postgres -
CREATE TABLE "Contest"
(
id serial NOT NULL,
name varchar(100) NOT NULL,
type char(1) NOT NULL,
status char(1) NOT NULL,
...
)
.
Sto cercando di ottenere valori di campo type
e status
Torna alla mia applicazione Play 2.x (ANORM):
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)
}
}
.
e ottieni errori:
could not find implicit value for parameter extractor: anorm.Column[Char]
.
Sembra che 'Char' non è supportato da ANUM.
Cosa dovrei cambiare nel mio codice?È buona pratica usare get[String]("status")
e poi status.head
come soluzione alternativa?
Soluzione
Penso che potresti scrivere un convertitore implicito per le tue colonne char
.Questo sarebbe simile a questo:
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))
}
})
}
.
Assicurarsi che questo convertitore sia in ambito.
Non sono sicuro che il valore sarebbe una stringa ma puoi controllarlo e creare le correzioni corrispondenti.
Altri suggerimenti
Viene recentemente fuso PR su Anem a riguardo: https://github.com/playframework/PlayFramework / Pull / 2189