Skip to content

Commit

Permalink
simplify cask scalasql integration
Browse files Browse the repository at this point in the history
  • Loading branch information
lihaoyi committed Jan 2, 2024
1 parent 96e95e3 commit 6f91d75
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 18 deletions.
14 changes: 5 additions & 9 deletions example/todo/app/src/TodoServer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,12 @@ object TodoServer extends cask.MainRoutes{
)

class transactional extends cask.RawDecorator{
class TransactionFailed(val value: cask.router.Result.Error) extends Exception
def wrapFunction(pctx: cask.Request, delegate: Delegate) = {
try sqliteClient.transaction( txn =>
delegate(Map("txn" -> txn)) match{
case cask.router.Result.Success(t) => cask.router.Result.Success(t)
case e: cask.router.Result.Error => throw new TransactionFailed(e)
}
)
catch{case e: TransactionFailed => e.value}

sqliteClient.transaction { txn =>
val res = delegate(Map("txn" -> txn))
if (res.isInstanceOf[cask.router.Result.Error]) txn.rollback()
res
}
}
}

Expand Down
16 changes: 7 additions & 9 deletions example/todoDb/app/src/TodoMvcDb.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,12 @@ object TodoMvcDb extends cask.MainRoutes{
)

class transactional extends cask.RawDecorator{
class TransactionFailed(val value: cask.router.Result.Error) extends Exception
def wrapFunction(pctx: cask.Request, delegate: Delegate) = {
try sqliteClient.transaction( txn =>
delegate(Map("txn" -> txn)) match{
case cask.router.Result.Success(t) => cask.router.Result.Success(t)
case e: cask.router.Result.Error => throw new TransactionFailed(e)
}
)
catch{case e: TransactionFailed => e.value}

sqliteClient.transaction { txn =>
val res = delegate(Map("txn" -> txn))
if (res.isInstanceOf[cask.router.Result.Error]) txn.rollback()
res
}
}
}

Expand Down Expand Up @@ -66,6 +62,8 @@ object TodoMvcDb extends cask.MainRoutes{
.returning(_.id)
.single
)

if (body == "FORCE FAILURE") throw new Exception("FORCE FAILURE BODY")
}

@transactional
Expand Down
3 changes: 3 additions & 0 deletions example/todoDb/app/test/src/ExampleTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ object ExampleTests extends TestSuite{

requests.post(s"$host/add", data = "new Task")

// Make sure endpoint failures do not commit their transaction
requests.post(s"$host/add", data = "FORCE FAILURE", check = false).statusCode ==> 500

requests.get(s"$host/list/active").text() ==>
"""[{"id":3,"checked":false,"text":"new Task"}]"""

Expand Down

0 comments on commit 6f91d75

Please sign in to comment.