How to express Postgres arrays with Scala Slick

前端 未结 2 1794
春和景丽
春和景丽 2021-01-03 17:06

I have a table in Postgres 9.5 with this structure:

my_table (id Integer, images_ranks image_rank[]);

where image_rank is:

相关标签:
2条回答
  • 2021-01-03 17:08

    What is ImageRank? Write its definition. I presume it's a case class

    case class ImageRank(imageUrl: String, thumbnailRank: Int)
    

    I guess that besides slick-pg mapper for specific array

    implicit val imageRankListTypeMapper =
      new AdvancedArrayJdbcType[ImageRank]("image_rank",
        str => utils.SimpleArrayUtils.fromString[ImageRank](s => {
          val ImageRankRegex = "ImageRank\\((.*),(\\d+)\\)".r
          s match {
            case ImageRankRegex(imageUrl, thumbnailRank) =>
              ImageRank(imageUrl, thumbnailRank.toInt)
            case _ =>
              println(s"$s is not ImageRank")
              ImageRank("", 0)
          }
        })(str).orNull,
        imageRanks => utils.SimpleArrayUtils.mkString[ImageRank](_.toString)(imageRanks)
      ).to(_.toList)
    

    you should define slick mapper for ImageRank like

    case class LiftedImageRank(imageUrl: Rep[String], thumbnailRank: Rep[Int])
    implicit object ImageRankShape extends CaseClassShape(LiftedImageRank.tupled, ImageRank.tupled)
    

    Documentation is here.

    SimpleArrayJdbcType has String argument meaning SQL base type so I guess "image_rank[]" won't work.

    Also SimpleArrayJdbcType works with arrays whose base type T is standard and for which ElemWitness[T] is defined in slick-pg. Since there is no ElemWitness[ImageRank] you should use AdvancedArrayJdbcType.

    0 讨论(0)
  • 2021-01-03 17:17

    The best would be for you to use this excellent library: https://github.com/tminglei/slick-pg

    If you would rather implement it yourself, have a look at the source code (https://github.com/tminglei/slick-pg/tree/master/core/src/main/scala/com/github/tminglei/slickpg/array) and get what you want from there.

    0 讨论(0)
提交回复
热议问题