WeiJ
WeiJ

Reputation: 1

Anorm: implicit convertion [all value(include null)] to [String]

I'm new to Scala and Play framework. I try to query all the data for selected columns from a data table and save them as Excel file.

Selected columns usually have different types, such as Int, Str, Timestamp, etc.

I want to convert all value types, include null into String (null convert to empty string "") without knowing the actual type of a column, so the code can be used for any tables.

According to Play's document, I can write the implicit converter below, however, this cannot handle null. Googled this for long time, cannot find solution. Can someone please let me know how to handle null in the implicit converter?

Thanks in advance~

implicit def valueToString: anorm.Column[String] =
    anorm.Column.nonNull1[String] { (value, meta) =>
        val MetaDataItem(qualified, nullable, clazz) = meta
        value match {
            case s: String              => Right(s) // Provided-default case
            case i: Int                 => Right(i.toString()) // Int to String
            case t: java.sql.Clob       => Right(t.toString()) // Blob/Text to String
            case d: java.sql.Timestamp  => Right(d.toString()) // Datatime to String
            case _                      => Left(TypeDoesNotMatch(s"Cannot convert $value: ${value.asInstanceOf[AnyRef].getClass} to String for column $qualified"))
        }

    }

Upvotes: 0

Views: 478

Answers (1)

cchantep
cchantep

Reputation: 9168

As indicated in the documentation, if there a Column[T], allowing to parse of column of type T, and if the column(s) can be null, then Option[T] should be asked, benefiting from the generic support as Option[T].

There it is a custom Column[String] (make sure the custom one is used, not the provided Column[String]), so Option[String] should be asked.

import myImplicitStrColumn
val parser = get[Option[String]]("col")

Upvotes: 1

Related Questions