Database.inTransaction

This commit is contained in:
Gwendal Roué committed 2015-07-01 08:22:03 +02:00
1 parent e00035b088
commit 4b2e90e54d
1 file changed
+43
+43
View File
@@ -9,6 +9,13 @@
typealias CConnection = COpaquePointer
public class Database {
public enum TransactionType {
case Deferred
case Immediate
case Exclusive
}
let cConnection = CConnection()
public init(path: String) throws {
@@ -32,4 +39,40 @@ public class Database {
public func updateStatement(sql: String) throws -> UpdateStatement {
return try UpdateStatement(database: self, sql: sql)
}
public func execute(sql: String) throws {
let statement = try updateStatement(sql)
try statement.execute()
}
public func inTransaction(type: TransactionType = .Exclusive, block: () throws -> Void) throws {
try beginTransaction(type)
do {
try block()
try commit()
} catch {
try rollback()
throw error
}
}
private func beginTransaction(type: TransactionType = .Exclusive) throws {
switch type {
case .Deferred:
try execute("BEGIN DEFERRED TRANSACTION")
case .Immediate:
try execute("BEGIN IMMEDIATE TRANSACTION")
case .Exclusive:
try execute("BEGIN EXCLUSIVE TRANSACTION")
}
}
private func rollback() throws {
try execute("ROLLBACK TRANSACTION")
}
private func commit() throws {
try execute("COMMIT TRANSACTION")
}
}