使用PostgreSQL的JSON类型与Slick 2代码生成器

6
我正在使用Slick 2代码生成器在我的Scala / Play应用程序中生成我的PostgreSQL数据库的表类。 然而,其中一些字段是JSON类型,并且它们被生成器转换为字符串。 我想知道是否可以通过slick-pg插件来让生成器识别Postgres JSON类型?
我尝试直接在Build.scala中扩展slick.driver.PostgresDriver
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"
    )
)       
2个回答

4
你无法以这种方式让生成器选择类型。它(或者更确切地说,从数据库模式反向工程出的 Model 的 Slick 代码)目前只能检测少量类型,并简单地假设所有其他类型都是字符串。未来将进行改进。为了使其使用不同类型的列,您需要自定义生成器。相应的 Slick 文档示例实际上展示了如何自定义类型:

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


1
在你提供的例子中,是否可以不针对列名而是针对列类型进行目标定位?类似这样:override def rawType = if (model.type == "SOME_SPECIAL_COLUMN_TYPE") "MyCustomType" else super.rawType - Caballero
模型只包含类型为Slick映射的内容,这种情况下可能是字符串。我认为这不是你想要的。你可以通过名称来获取,或者通过JDBC请求模式元数据。你可以使用这个Slick助手:http://slick.typesafe.com/doc/2.0.0/api/index.html#scala.slick.jdbc.meta.MColumn$ - cvogt
1
@cvogt 我也遇到了同样的问题,SERIAL 被映射为 Int,而实际上它应该是 Long。通过列名来解决这个问题远非理想,而且可能效果不佳。你能否提供一个使用 JDBC 元数据的示例呢? - Akos Krivachy
Slick附带了jdbc的DatabaseMetaData api的包装器。请参见http://slick.typesafe.com/doc/2.0.1/api/#scala.slick.jdbc.meta.package 这里是一些使用它的地方:https://github.com/slick/slick/blob/master/slick-testkit/src/test/scala/scala/slick/test/jdbc/MetaTest.scala https://github.com/slick/slick/blob/9145c8162d3e5028e890222b28ca3d4cfe20170c/src/main/scala/scala/slick/driver/JdbcProfile.scala#L60 https://github.com/slick/slick/blob/master/src/main/scala/scala/slick/jdbc/meta/package.scala - cvogt

0
你也可以定义一个函数直接访问json树。
val jsonSQL=
SimpleFunction.binary[Option[String],String,Option[String]]("json_extract_path_text")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接