diff --git a/GRDB/Database.swift b/GRDB/Database.swift index 1705dc85e..85e662455 100644 --- a/GRDB/Database.swift +++ b/GRDB/Database.swift @@ -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") + } + }