Skip to content

Commit

Permalink
Add block transaction helper
Browse files Browse the repository at this point in the history
A series of statements is not always enough. Sometimes you need
application logic in there.

    db.transaction { _ in
        // ...
        return success ? .Commit : .Rollback
    }

Signed-off-by: Stephen Celis <stephen@stephencelis.com>
  • Loading branch information
stephencelis committed Feb 5, 2015
1 parent e0bb518 commit c5881a8
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions SQLite Common/Database.swift
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ public final class Database {

}

public enum TransactionResult: String {

case Commit = "COMMIT TRANSACTION"

case Rollback = "ROLLBACK TRANSACTION"

}

/// Runs a series of statements in a transaction. The first statement to
/// fail will short-circuit the rest and roll back the changes. A successful
/// transaction will automatically be committed.
Expand Down Expand Up @@ -253,12 +261,16 @@ public final class Database {
///
/// :returns: The last statement executed, successful or not.
public func transaction(mode: TransactionMode, _ statements: [@autoclosure () -> Statement]) -> Statement {
var transaction = run("BEGIN \(mode.rawValue) TRANSACTION")
// FIXME: rdar://15217242 // for statement in statements { transaction = transaction && statement() }
for idx in 0..<statements.count { transaction = transaction && statements[idx]() }
transaction = transaction && run("COMMIT TRANSACTION")
if transaction.failed { run("ROLLBACK TRANSACTION") }
return transaction
var statement: Statement!
let result = transaction(mode) { transaction in
statement = reduce(statements, transaction, &&)
return statement.failed ? .Rollback : .Commit
}
return statement && result
}

public func transaction(_ mode: TransactionMode = .Deferred, block: Statement -> TransactionResult) -> Statement {
return run(block(run("BEGIN \(mode.rawValue) TRANSACTION")).rawValue)
}

// MARK: - Savepoints
Expand Down

0 comments on commit c5881a8

Please sign in to comment.