Last Updated: February 25, 2016
·
1.619K
· ahmad_ragab

Slick 3.1.1 Codegen for Views

Slick 3.1.1 has some fairly nice tools for generating your ddl and schema code from an already existing database. One thing that is a bit tricky, is when you have some very database specific field types in your db or you want slick to work on top of views.

To do it, you have to rely on MTables (m for meta), to get both Tables and Views straight away.

import slick.codegen.SourceCodeGenerator
import slick.driver.PostgresDriver
import slick.driver.PostgresDriver.api._
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import slick.jdbc.meta._

object CreateModel extends App {

  override def main(args: Array[String]) {
    // fetch data model
  String dbConfig = "your_db_config" //in application.conf
    val db = Database.forConfig(dbConfig)
    val tablesAndViews = MTable.getTables(None, None, None, Some(Seq("TABLE", "VIEW"))) //TABLE, and VIEW represent metadata, i.e. get database objects which are tables and views
    val modelAction = PostgresDriver.createModel(Some(tablesAndViews))
    val modelFuture = db.run(modelAction) //slick has drivers and extensions for a number of dbs including mysql, MSSQL, H2 and Oracle

    // customize code generator
    val codegenFuture = modelFuture.map(model => new SourceCodeGenerator(model))

    val path = getClass.getResource("").getPath

    Await.ready(
      codegenFuture.map(_.writeToFile("slick.driver.PostgresDriver", path, "dal", "Tables", "Tables.scala")), 20 seconds)
  }

}

As it stands this runs as a standalone program, there is a possibility of sbt integration to run on compile for example, however, that requires a bit more finessing. See documentation (linked above) for more.