A Transaction acquired in a try, committed or rolled back

The complete source of dependencyInjection_transaction.ek9, compiled by the EK9 compiler. Shown on dependencyInjection.html.

#!ek9
defines module site.dependencyInjection.transaction

  defines class

    DatabaseTransaction with trait of Transaction
      connectionName <- String()
      committed <- false

      DatabaseTransaction()
        -> connectionName as String
        this.connectionName: connectionName

      execute()
        -> statement as String
        Stdout().println(`${connectionName}: ${statement}`)

      override commit()
        execute("COMMIT")
        committed: true

      override rollback()
        execute("ROLLBACK")
        committed: false

      override isCommitted() as pure
        <- rtn as Boolean: Boolean(committed)

      default operator ?

  defines function

    updateRecords()
      ->
        txn as DatabaseTransaction
        amount as Integer
      txn.execute(`UPDATE accounts SET balance = ${amount}`)
      if amount < 0
        throw Exception("a balance cannot be negative")

  defines program

    Demo()
      stdout <- Stdout()
      for amount in [100, -5]
        try
          -> txn <- DatabaseTransaction("primary-db")
          try
            updateRecords(txn, amount)
            txn.commit()
          catch
            -> ex as Exception
            txn.rollback()
            stdout.println(`Transaction failed: ${ex}`)

Download dependencyInjection_transaction.ek9

Output

primary-db: UPDATE accounts SET balance = 100
primary-db: COMMIT
primary-db: UPDATE accounts SET balance = -5
primary-db: ROLLBACK
Transaction failed: Exception: a balance cannot be negative