spydon
spydon

Reputation: 11512

Slick code generation with multiple identical schemas

I have multiple identical schemas, but when Slick generates the classes it hardcodes a schema in there so that I can't use it with a different schema.

For example: class User(_tableTag: Tag) extends profile.api.Table[UserRow](_tableTag, Some("custom"), "user") { ...

There custom is the schema name, and if I change that to None it will take the schema from the db connection string instead.

How can I get the Slick code generator to generate all classes with None instead of with the hard coded schema name?

Upvotes: 0

Views: 176

Answers (1)

wmmeyer
wmmeyer

Reputation: 466

You can override def createModelBuilder in your JdbcProfile. The PostgresProfile included with slick already does this to remove the schema from the generated table definition if its == "public".

https://github.com/slick/slick/blob/14db18d7974ade35bf6d6dbc97bfe6e0490807c8/slick/src/main/scala/slick/jdbc/PostgresProfile.scala

trait PostgresProfile extends JdbcProfile {

  // line 61
  class ModelBuilder(mTables: Seq[MTable], ignoreInvalidDefaults: Boolean)(implicit ec: ExecutionContext) extends JdbcModelBuilder(mTables, ignoreInvalidDefaults) {

    override def createTableNamer(mTable: MTable): TableNamer = new TableNamer(mTable) {
      override def schema = super.schema.filter(_ != "public") // remove default schema
    }

  }

  // line 139
  override def createModelBuilder(tables: Seq[MTable], ignoreInvalidDefaults: Boolean)(implicit ec: ExecutionContext): JdbcModelBuilder =
    new ModelBuilder(tables, ignoreInvalidDefaults)

}

You should be able to do something similar in a custom profile

trait NoSchemaProfile extends MyDatabaseProfile {

  class NoSchemaModelBuilder(mTables: Seq[MTable], ignoreInvalidDefaults: Boolean)(implicit ec: ExecutionContext) extends super.ModelBuilder(mTables, ignoreInvalidDefaults) {

    override def createTableNamer(mTable: MTable): TableNamer = new TableNamer(mTable) {
      override def schema = Option.empty[String]
    }

  }

  override def createModelBuilder(tables: Seq[MTable], ignoreInvalidDefaults: Boolean)(implicit ec: ExecutionContext): JdbcModelBuilder =
    new NoSchemaModelBuilder(tables, ignoreInvalidDefaults)
  }
}

and then specify the custom profile when you generate the code

Upvotes: 1

Related Questions