Emm...I'm trying out Slick with Play 2. The table creation process has become very frustrating because unlike other ORM (like ebean), Slick doesn't detect if the database is created, if there is already a table existing, it will report an exception. I simply just don't want to drop and create every time I restart the server, so I decide to write a small function to help me:
def databaseCreate(tables: Table*) = {
for (table <- tables) {
if (MTable.getTables(table.getClass.getName).list.isEmpty) table.ddl.create
}
}
What this does is to take in some objects like this one:
object Tag extends Table [(Option[Int], String)]("Tags") {
def id = column[Int]("TAG_ID", O.PrimaryKey, O.AutoInc)
def tag_name = column[String]("TAG_NAME")
def * = id.? ~ tag_name
}
And use MTable
method from scala.slick.jdbc.meta.MTable
to know if the table exists or not. Then I kinda run into a simple Java reflection problem. If databaseCreate
method takes Strings, then I can invoke .ddl.create
. So I decide to pass in objects and use relfection:table.getClass.getName
. The only problem is there is a type mismatch: (from my IDE)
Expected: MySQLDriver.simple.type#Table, actual: BlogData.Tag.type
BlogData is the big object I used to store all smaller table objects. How do I solve this mismatch problem?? Use a whole bunch of asInstanceOf
? It would make the command unbearably long and ugly...
I also posted this on StackOverflow if you want to answer it somewhere else... (I'm new to Scala btw) http://stackoverflow.com/questions/20694323/slick-write-a-simple-table-creation-function