【问题标题】:Use PostgreSQL JSON type with Slick 2 code generator将 PostgreSQL JSON 类型与 Slick 2 代码生成器一起使用
【发布时间】:2014-04-21 22:57:51
【问题描述】:

我在我的 Scala/Play 应用程序中使用Slick 2 code generator 来生成我的 PostgreSQL 数据库的表类。有些字段虽然是 JSON 类型,但它们会被生成器转换为字符串。我想知道我是否可以以某种方式使用slick-pg plugin 使生成器识别 Postgres JSON 类型?

我尝试将slick.driver.PostgresDriver 直接扩展为Build.scala:

import slick.driver.PostgresDriver
import com.github.tminglei.slickpg._

trait MyPostgresDriver extends PostgresDriver
                          with PgArraySupport
                          with PgDateSupport
                          with PgRangeSupport
                          with PgHStoreSupport
                          with PgPlayJsonSupport
                          with PgSearchSupport
                          with PgPostGISSupport {

  override val Implicit = new ImplicitsPlus {}
  override val simple = new SimpleQLPlus {}

  trait ImplicitsPlus extends Implicits
                        with ArrayImplicits
                        with DateTimeImplicits
                        with RangeImplicits
                        with HStoreImplicits
                        with JsonImplicits
                        with SearchImplicits
                        with PostGISImplicits

  trait SimpleQLPlus extends SimpleQL
                        with ImplicitsPlus
                        with SearchAssistants
                        with PostGISAssistants
}

object MyPostgresDriver extends MyPostgresDriver

但我不知道如何将它与代码生成器例程而不是标准驱动程序一起使用:

SourceCodeGenerator.main(
    Array(
        "scala.slick.driver.PostgresDriver", //how do I use MyPostgresDriver here?
        "org.postgresql.Driver", 
        "jdbc:postgresql://localhost:5432/db?user=root&password=root", 
        "app", 
        "db"
    )
)       

【问题讨论】:

    标签: json postgresql scala playframework slick


    【解决方案1】:

    您不能以这种方式让生成器拾取类型。它(或者更确切地说是从数据库模式中对模型进行逆向工程的 Slick 代码)目前只检测到一个充满类型的手,并简单地将所有其他类型假定为 String。这将在未来得到改善。为了使它对列使用不同的类型,您必须自定义生成器。对应的 Slick 文档示例实际上展示了如何自定义类型:

    http://slick.typesafe.com/doc/2.0.0/code-generation.html#customization

    【讨论】:

    【解决方案2】:

    也可以定义一个函数直接访问json树

    val jsonSQL=
    SimpleFunction.binary[Option[String],String,Option[String]]("json_extract_path_text")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-16
      • 2020-02-29
      • 2015-02-09
      • 1970-01-01
      • 2022-01-15
      • 2018-11-24
      • 1970-01-01
      • 2018-04-28
      相关资源
      最近更新 更多