Accessing database metadata

Commonly, especially during development, you might start the script by dropping the table if it exists, then recreating it. We can find if a table is defined by accessing the database metadata through the MTable object. To get a list of tables with name matching a certain pattern, we can run MTable.getTables(pattern):

scala> import slick.jdbc.meta.MTable
import slick.jdbc.meta.MTable

scala> db.withSession { implicit session =>
  MTable.getTables("transactions").list
}
List[scala.slick.jdbc.meta.MTable] = List(MTable(MQName(fec.transactions),TABLE,,None,None,None) ...)

Thus, to drop the transactions table if it exists, we can run the following:

scala> db.withSession { implicit session =>
  if(MTable.getTables("transactions").list.nonEmpty) {
    Tables.transactions.ddl.drop
  }
}

The MTable instance contains a lot of metadata about the table. Go ahead and recreate the transactions table if you dropped it in the previous example. Then, to find information about the table's primary keys:

scala> db.withSession { implicit session =>
  val tableMeta = MTable.getTables("transactions").first
  tableMeta.getPrimaryKeys.list
}
List[MPrimaryKey] = List(MPrimaryKey(MQName(test.transactions),id,1,Some(PRIMARY)))

For a full list of methods available on MTable instances, consult the Slick documentation (http://slick.typesafe.com/doc/2.1.0/api/index.html#scala.slick.jdbc.meta.MTable).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.101.109