Search code examples
scalaslick

Slick provide table schema name parameter


I am able to create a Slick table if I hard-code the schema name, but how can I pass it in as a parameter?

The code below works, but the schema name is hard-coded. Since I use one schema as my development environment, and a different schema for production, I would like to pass in the schema name as a parameter. But if I add a second parameter to the constructor, I can no longer instantiate the class, because I don't know how to get an instance of slick.lifted.Tag. (When the constructor has only one parameter - the Tag - the value is provided automatically by a macro.)

class SomeTableTbl(tag: Tag) extends Table[SomeRecord](tag, _schemaName = Some("MY_DEV_SCHEMA"), _tableName = "SOME_TABLE") {
  def record_id: Rep[Long] = column[Long]("RECORD_ID", O.PrimaryKey, O.AutoInc)

  def column_one: Rep[String] = column[String]("COLUMN_ONE")

  def column_two: Rep[String] = column[String]("COLUMN_TWO")

  def column_six: Rep[String] = column[String]("COLUMN_SIX")

  override def * : ProvenShape[SomeRecord] = (record_id, column_one, column_two, column_six) <> (SomeRecord.tupled, SomeRecord.unapply)
}

// works, "tag: slick.lifted.Tag" param is provided by some macro
lazy val tblQuery: TableQuery[SomeTableTbl] = TableQuery[SomeTableTbl]
// Now add constructor parameter: SomeTableTbl(tag: Tag, schemaName: String)
lazy val tblQuery: TableQuery[SomeTableTbl] = TableQuery[SomeTableTbl]("some_other_schema_name")
// Error: not enough arguments for constructor

How can I provide a schemaName parameter to the constructor and create instances of this class? Using Scala 2.12, Slick 3.3.0


Solution

  • Object TableQuery has two variants of the method apply. One of them accepts a function from a tag to an instance of a table, so the following should work:

    lazy val tblQuery: TableQuery[SomeTableTbl] =
      TableQuery(tag => new SomeTableTbl(tag, "other_schema_name"))