scala – 如何使用Slick代码生成器来包含数据库视图?

我正在尝试使用Slick 3.0.3为我的架构中的数据库表和视图生成Scala代码.以this blog为例,我有以下文件build.sbt.但是,这将为我的数据库表生成代码,并且不包括数据库视图.如何获得生成的视图?

根据slick issue 1022我发现它可以做,但API看起来并不相似,而且slick.codegen.SourceCodeGenerator没有getTables或defaultTables来包含视图名称.

name := "slickCodeGen"

version := "1.0"

scalaVersion := "2.11.6"

scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")

libraryDependencies ++= Seq(
  "com.typesafe.slick" %% "slick" % "3.0.3",
  "com.typesafe.slick" %% "slick-codegen" % "3.0.3",
  "org.postgresql" %  "postgresql" % "9.4-1201-jdbc41",
  "com.zaxxer" % "HikariCP" % "2.3.2",
  "org.scalatest" %% "scalatest" % "2.2.4" % "test"
)

slick <<= slickCodeGenTask

sourceGenerators in Compile <+= slickCodeGenTask

lazy val slick = TaskKey[Seq[File]]("gen-tables")
lazy val slickCodeGenTask = (sourceManaged, dependencyClasspath in Compile, runner in Compile, streams) map { (dir, cp, r, s) =>
  val outputDir = (dir / "main/slick").getPath
  val username = "postgres"
  val password = "xxx"
  val url = "jdbc:postgresql://localhost:5555/testdb?searchpath=public"
  val jdbcDriver = "com.postgresql.jdbc.Driver"
  val slickDriver = "slick.driver.PostgresDriver"
  val pkg = "folder1.folder2"
  toError(r.run("slick.codegen.SourceCodeGenerator", cp.files, Array(slickDriver, jdbcDriver, url, outputDir, pkg, username, password), s.log))
  val fname = outputDir + "/folder1/folder2/" + "Tables.scala"
  Seq(file(fname))
}
最佳答案
经过大量的试验和错误,由于Slick生成器API的许多变化,以下独立的应用程序Generator.scala测试将生成Slick 3.0.3下的表和视图的代码:

import java.util.concurrent.TimeUnit

import slick.driver.PostgresDriver
import slick.jdbc.meta.MTable
import slick.codegen.SourceCodeGenerator
import slick.driver.PostgresDriver.simple._
import play.api.libs.concurrent.Execution.Implicits._

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

object Generator extends App {
  val slickDriver = "slick.driver.PostgresDriver"
  val jdbcDriver = "org.postgresql.Driver"
  val url = "jdbc:postgresql://localhost:5555/testdb?searchpath=public"
  val outputDir = "/tmp/"
  val pkg = "folder1.folder2"
  val username = "postgres"
  val password = "xxx"

  val db = Database.forURL(url, user, password)
  val dbio = PostgresDriver.createModel(Some(MTable.getTables(None, None, None, Some(Seq("TABLE", "VIEW")))))
  val model = db.run(dbio)
  val future : Future[SourceCodeGenerator] = model.map(model => new SourceCodeGenerator(model))
  val codegen : SourceCodeGenerator = Await.result(future, Duration.create(5, TimeUnit.MINUTES))
  codegen.writeToFile(slickDriver, outputDir, pkg, "Tables", "Tables.scala")
}

将此代码集成到build.sbt并不是那么容易,因为需要定义外部自定义代码生成器文件,然后在编译实际项目之前从build.sbt编译并运行它.一个非常过时的例子可以在github项目slick-codegen-customization-example中找到,但请注意它们没有build.sbt但是更高级的Build.scala

转载注明原文:scala – 如何使用Slick代码生成器来包含数据库视图? - 代码日志