Using Squeryl to create database DDL

Squeryl has Schema.create helper method which creates and executes DDL statements for each table defined in the schema. Unfortunately, that does not work if your application's user does not have rights to execute any DDL statements. In that case you may create the schema manually. But that is a mundane process and since you already have DB structure defined why not save yourself some trouble manually mapping column names ant types and use Squeryl to your advantage?

I would like Squeryl to log those DDL statements without trying to execute them. Here is the helper method to do just that:

object MySchema extends Schema {
  val users = table[User]("users")
  val books = table[Book]("books")
  ...

  def logCreate {
    val adaptor = new PostgreSqlAdapter
    for (t <- tables) {
      val sw = new StatementWriter(adaptor)
      adaptor.writeCreateTable(t, sw, this)
      log.debug(sw.statement)
    }
  }
}

You can go further and print out sequence creation statements, FK relations and so on. But I decided to stop right here. That is huge help to have DDL statements for the DB my ORM layer expects. I am going to go over them and tweak them a lot anyway ;)

P.S. Of course you could have had a temporary database with DDL-enabled user and you would execute Schema.create to see the log output. Whichever is easier for you.

P.P.S. Btw, here is how to initialize Squeryl with C3P0 pool and sql logging enabled:

// Database companion object. Import it to have access to DB DSL 
object Database extends PrimitiveTypeMode {

  val log = LogManager.getLogger

  def init {
    val cpds = new ComboPooledDataSource
    cpds.setDriverClass("org.postgresql.Driver")
    cpds.setJdbcUrl("jdbc:postgresql://host:5432/mydb")
    cpds.setUser("myuser")
    cpds.setPassword("mypassword")
    org.squeryl.SessionFactory.concreteFactory = Some(() => {
      val session = Session.create(cpds.getConnection, new PostgreSqlAdapter)
      // Enable SQL logging
      session.setLogger((sql: String) => Database.log.debug("SQL: {}", sql))
      session
    })
  }

}