File: ExampleSpec.scala

package info (click to toggle)
libpgjava 42.2.5-2%2Bdeb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 8,136 kB
  • sloc: java: 57,821; xml: 1,135; sh: 307; perl: 99; makefile: 7
file content (74 lines) | stat: -rw-r--r-- 1,982 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import anorm._
import org.scalatest._
import org.scalatestplus.play._
import play.api.db._
import play.api.libs.json._
import play.api.test._
import play.api.test.Helpers._
import scala.util.{Failure, Success, Try}

case class Example(
  data: JsValue
)

class ExampleSpec extends PlaySpec with OneAppPerSuite {

  import scala.concurrent.ExecutionContext.Implicits.global

  "example" in {
    DB.withConnection { implicit c =>
      SQL("drop table if exists pgbugkeystore").execute()
      SQL("create table pgbugkeystore(data json)").execute()
      SQL("insert into pgbugkeystore (data) values ({data}::json)").on(
        'data -> "{}"
      ).executeUpdate()

      SQL("select data from pgbugkeystore").as(
        SqlParser.get[JsObject]("data").*
      )
    }
  }

  implicit val columnToJsObject: Column[play.api.libs.json.JsObject] = Util.parser { _.as[play.api.libs.json.JsObject] }

  /**
    * Conversions to collections of objects using JSON.
    */
  object Util {

    def parseJson[T](f: play.api.libs.json.JsValue => T, columnName: String, value: String) = {
      Try {
        f(
          play.api.libs.json.Json.parse(value)
        )
      } match {
        case Success(result) => Right(result)
        case Failure(ex) => Left(
          TypeDoesNotMatch(
            s"Column[$columnName] error parsing json $value: $ex"
          )
        )
      }
    }

    def parser[T](
      f: play.api.libs.json.JsValue => T
    ) = anorm.Column.nonNull { (value, meta) =>
      val MetaDataItem(columnName, nullable, clazz) = meta
      value match {
        case json: org.postgresql.util.PGobject => parseJson(f, columnName.qualified, json.getValue)
        case _=> {
          Left(
            TypeDoesNotMatch(
              s"Column[${columnName.qualified}] error converting $value to Json. Expected class to be[org.postgresql.util.PGobject] and not[${value.asInstanceOf[AnyRef].getClass}"
            )
          )
        }


      }
    }

  }
  
}