suish
suish

Reputation: 3343

scala slick handling more than 2 same structure tables by one model

I'm trying achieve something like log tables.

Let's say I have...

final class LogTable(tag: Tag) extends Table[LogModel](tag,"log"){
  def createdAt = column[Timestamp]("created_at")
  //...
}

Since log gets too many records for a single table, I want to use multiple tables which has exactly same structure but different names. in another way to say, I want to change only Table[](tag,"this name") and If it's possible, I want to let it act like a single table when it gets called from outside.

current my implementation

class LogBase(tag: Tag) extends Table[LogModel](tag,"log"){
  def createdAt = column[Timestamp]("created_at")
  //...
}

final class LogTable1(tag:Tag) extends LogBase(tag){
  override val tableName = "log1"
}

final class LogTable2(tag:Tag) extends LogBase(tag){
  override val tableName = "log2"
}

//...

writing tables as many as I need is a last option though, is there any way to achieve this in a smart way?

any kind of suggestion is appreciated.

Upvotes: 2

Views: 433

Answers (2)

suish
suish

Reputation: 3343

like the way nmat mentioned, making a table class generator class solve the problem.

class LogBase(tableNum: Int){
  class LogTable(tag: Tag) extends Table[LogModel](tag,s"log$tableNum"){
    def createdAt = column[Timestamp]("created_at")
    //...
  }
}  

and how to use it

val tables = (1 to 10).toList.map { num =>
  val clazz = new LogBase(num)
  TableQuery[clazz.LogTable]
}

Upvotes: 1

nmat
nmat

Reputation: 7591

Why don't you simply pass the table name as an argument?

class LogBase(tag: Tag, id: Int) extends Table[LogModel](tag, s"log${id % 100}")

You can create a factory to abstract this logic

Upvotes: 1

Related Questions