9

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

tonicebrian
  • 4,715
  • 5
  • 41
  • 65
  • 3
    But the latest 0.9.4 Session has still a rollback method on it (http://scalaquery.org/doc/api/scalaquery-0.9.4/org/scalaquery/session/Session.html). Isn't that enough? – VonC May 17 '11 at 11:42
  • 1
    Ok, I thought that rollback didn't exist because I could not find it with the search functionality of the ScalaDocs. Now I'm trying the rollback for the threadLocalSession but it says that I can not rollback with an auto-commit session, and I don't know were this option was selected. Any code example could help a lot. Thanks!! – tonicebrian May 18 '11 at 06:58

1 Answers1

2

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)
    }
  }
}
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
tonicebrian
  • 4,715
  • 5
  • 41
  • 65