Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rollback a session in ScalaQuery?

For my unit tests I want to setup a database, populate it with base information and run each tests within a session that rollbacks all changes made to the DB in order to always have a pristine copy for each tests.

I'm looking for something like

db withSession {
   <create my objects under test>
   <run operations>
   <run asserts>

   this.rollback()
}

The rollback function was in early versions of Scala Query but it seems that it is missing now. How should I implement this functionality?

Best regards

like image 528
tonicebrian Avatar asked May 17 '11 09:05

tonicebrian


1 Answers

Here is a unit test that illustrates this behaviour

https://github.com/szeiger/scala-query/blob/master/src/test/scala/org/scalaquery/test/TransactionTest.scala

GitHub currently 404s on the link, but I pulled the source code out of the google cache:

package org.scalaquery.test

import org.junit.Test
import org.junit.Assert._
import org.scalaquery.ql._
import org.scalaquery.ql.extended.{ExtendedTable => Table}
import org.scalaquery.session.Database.threadLocalSession
import org.scalaquery.test.util._
import org.scalaquery.test.util.TestDB._

object TransactionTest extends DBTestObject(H2Disk, SQLiteDisk, Postgres, MySQL, DerbyDisk, HsqldbDisk, MSAccess, SQLServer)
class TransactionTest(tdb: TestDB) extends DBTest(tdb) {
  import tdb.driver.Implicit._

  @Test def test() {

    val T = new Table[Int]("t") {
      def a = column[Int]("a")
      def * = a
    }

    db withSession {
      T.ddl.create
    }

    val q = Query(T)

    db withSession {
      threadLocalSession withTransaction {
        T.insert(42)
        assertEquals(Some(42), q.firstOption)
        threadLocalSession.rollback()
      }
      assertEquals(None, q.firstOption)
    }
  }
}
like image 176
tonicebrian Avatar answered Oct 19 '22 19:10

tonicebrian