问题描述
我在 Postgres 9.5 中有一个具有这种结构的表:
I have a table in Postgres 9.5 with this structure:
my_table (id Integer, images_ranks image_rank[]);
其中 image_rank
是:
CREATE TYPE image_rank AS (image_url text, thumbnail_rank integer);
我很难在 Slick (3.1) 中表达类似的东西:
I am struggling to express something like that in Slick (3.1):
case class MyTable (id: Int, imagesRanks: Seq[Option[ImageRank]])
implicit val propertyMyTableResult = GetResult(r => MyTable(r.<<, r.<<)
implicit val propertyImageRankResult = GetResult[Option[ImageRank]] { r => ImageRank(r.<<, r.<<)) }
正确的做法是什么?
更新
这个包装(遵循 n1r3 的答案)目前阻止了我:
This wrap (following the answer from n1r3) is blocking me at the moment:
implicit val ImageRankWrapper: JdbcType[List[ImageRank]] = new SimpleArrayJdbcType[ImageRank]("image_rank[]").to(_.toList)
更新 2
还是不知道哪里出了问题.我已经按照你的建议添加了代码,但它仍然抱怨:
Still not sure what is wrong. I have added the code as you suggested, but it still complains with:
找不到参数 rconv 的隐式值:slick.jdbc.GetResult[database.rows.MyTable]
.
所以我添加了:
隐式 val myTableResult = GetResult[MyTable](r => MyTable(r.<<, r.<<))
返回:
diverging implicit expansion for type slick.jdbc.GetResult[T1]
starting with object GetStringOption in object GetResult
r.<<, r.<<))
这是我的配置:
import com.github.tminglei.slickpg._
import database.rows.ImageRank
trait CustomPostgresProfile extends ExPostgresProfile
with PgArraySupport
with PgPlayJsonSupport
with PgPostGISSupport
with PgEnumSupport
with PgDate2Support {
// Use PostgreSQL JSONB support
def pgjson = "jsonb"
override val api = MyAPI
object MyAPI extends API
with ArrayImplicits
with JsonImplicits
with PostGISImplicits
with DateTimeImplicits {
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)
}
}
object CustomPostgresProfile extends CustomPostgresProfile
abstract class DatabaseProfile(val provider: DatabaseConfigProvider) {
val config = provider.get[CustomPostgresProfile]
val profile = config.profile
val db = config.db
}
trait PropertyDataDatabase {
self: DatabaseProfile =>
.....
推荐答案
最好使用这个优秀的库:https://github.com/tminglei/slick-pg
The best would be for you to use this excellent library: https://github.com/tminglei/slick-pg
如果您更愿意自己实现,请查看源代码(https://github.com/tminglei/slick-pg/tree/master/core/src/main/scala/com/github/tminglei/slickpg/array) 并从那里得到你想要的.
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.
这篇关于如何使用 Scala Slick 表达 Postgres 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!