Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute DDL only when tables don't exist?

I'm using Slick 1.0 with Play Framework 2.1 and MySQL.

I'd like to control the ddl table creation so that it only takes place if the tables don't exist. That is to say that the tables should only get created the first time I start play.

How to do it in Slick?

like image 803
Magnus Smith Avatar asked Mar 14 '13 11:03

Magnus Smith


2 Answers

Since I like to control the creation of my tables individually and keep it DRY, I just tend to add a utility method to my apps:

def createIfNotExists(tables: TableQuery[_ <: Table[_]]*)(implicit session: Session) {
  tables foreach {table => if(MTable.getTables(table.baseTableRow.tableName).list.isEmpty) table.ddl.create}
}

Then you can just create your tables with the implicit session:

db withSession {
  implicit session =>
    createIfNotExists(table1, table2, ..., tablen)
}
like image 189
Michael Jess Avatar answered Oct 26 '22 06:10

Michael Jess


For the benefit of others SLICK provides an MTable Object that you can use to count the number of tables present in your database.

You can then conditionally call the ddl if they are not present. In the case below I expect to have 11 tables + the play_evolutions table

import scala.slick.jdbc.meta._

 if (MTable.getTables.list().size < 12) {
        (Contacts.ddl ++ ThirdParties.ddl ++ Directorates.ddl ++ ServiceAreas.ddl ++ ICTServers.ddl
          ++ ICTServerDependencies.ddl ++ ICTSystems.ddl ++ ICTSystemDependencies.ddl ++ ICTSystemServerDependencies.ddl
              ++ CouncilServices.ddl ++ CouncilServiceDependencies.ddl).create
}
like image 25
Magnus Smith Avatar answered Oct 26 '22 08:10

Magnus Smith