How to express Postgres arrays with Scala Slick

前端 未结 2 1793
春和景丽
春和景丽 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.

提交回复
热议问题