Question

I'd like to add a second temporary DB (filebased H2) to our Play 2.1 app. But can't figure out how and where to create a Squeryl schema for the second DB.

The first schema is already defined in a scala class that extends org.squeryl.Schema. Where should I put table definitions for the second DB?

Thanks for any hints.

Was it helpful?

Solution

I've not used Play so you may need to tweak this around a bit to get it to work, but you should be able to create a new session for that database, something like:

object MySecondDBSchema extends SquerylSchema with SchemaDefaults {
  def newSession[A](f: => A) =  {
    transaction(new org.squeryl.Session(//get java.sql.Connection, new H2Adapter)) {
      f
    }
  }

  val myTable = table[MyTable]
}

or, if you just want a connection and plan to deal with transactions on your own.

def newSession[A](f: => A) =  {
  using(new org.squeryl.Session(//get java.sql.Connection, new H2Adapter)) {
    //start your own transaction
    f
  }
}

Then in your code, when you want to access that other database you can wrap your queries in that:

def myMethodToAccessFirstDB() = {
  import MySecondDBSchema._

  newSession{ 
    //access alternate database
    from(myTable)(t => select(t)).toList 
  }
}

def myMethodToAccessDefaultDB() = {
  import DefaultSchema._ //Or whatever your default Schema is named

  //access default database
  from(otherTable)(ot => select(ot))
}

It is logical to define and organize the tables in a second object that extends org.squeryl.Schema but any query made within the newSession block will be performed against the second database.

As for overriding the name attribute, that will change the default schema in the database but is not necessary for creating a separate Squeryl schema.

OTHER TIPS

In addition to jcern answer: don't forget to close connection. My variant:

object MySecondDBSchema extends Schema {

  var ds : DataSource = _

  def newSession[A](f: => A) = {
    var conn: Option[Connection] = None
    try {
      conn = Some(ds.getConnection)
      val proxyConn = conn.map {
        case a : ArraySupportProxyConnection => a
        case c : C3P0ProxyConnection => new ArraySupportProxyConnection(c)
      }.get
      using[A](new org.squeryl.Session(proxyConn, new AwesomePostgreSqlAdapter)) {
        inTransaction {
          f
        }
      }
    }
    finally {
      conn.foreach(_.close())
    }
  }

  ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top