Conditional Operations

Modifying operations (Put, Delete, Update) can be performed conditionally, so that they only have an effect if some state of the DynamoDB table is true at the time of execution.

import com.gu.scanamo._
import com.gu.scanamo.syntax._
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType._
val client = LocalDynamoDB.client()
case class Gremlin(number: Int, name: String, wet: Boolean, friendly: Boolean)
val gremlinsTable = Table[Gremlin]("gremlins")
// gremlinsTable: com.gu.scanamo.Table[Gremlin] = Table(gremlins)

LocalDynamoDB.withTable(client)("gremlins")('number -> N) {
  val ops = for {
    _ <- gremlinsTable.putAll(
      Set(Gremlin(1, "Gizmo", false, true), Gremlin(2, "George", true, false)))
    // Only `put` Gremlins if not already one with the same number
    _ <- gremlinsTable.given(not(attributeExists('number)))
      .put(Gremlin(2, "Stripe", false, true))
    _ <- gremlinsTable.given(not(attributeExists('number)))
      .put(Gremlin(3, "Greta", true, true))
    allGremlins <- gremlinsTable.scan()  
    _ <- gremlinsTable.given('wet -> true)
      .delete('number -> 1)
    _ <- gremlinsTable.given('wet -> true)
      .delete('number -> 2)
    _ <- gremlinsTable.given('wet -> true)
      .update('number -> 1, set('friendly -> false))
    _ <- gremlinsTable.given('wet -> true)
      .update('number -> 3, set('friendly -> false))
    remainingGremlins <- gremlinsTable.scan()
  } yield (allGremlins, remainingGremlins)
  Scanamo.exec(client)(ops)
}
// res0: (List[Either[com.gu.scanamo.error.DynamoReadError,Gremlin]], List[Either[com.gu.scanamo.error.DynamoReadError,Gremlin]]) = (List(Right(Gremlin(2,George,true,false)), Right(Gremlin(1,Gizmo,false,true)), Right(Gremlin(3,Greta,true,true))),List(Right(Gremlin(1,Gizmo,false,true)), Right(Gremlin(3,Greta,true,false))))

More examples can be found in the Table ScalaDoc.