From 4b2e90e54d8521fc3137b1928cd6afeb6bdcefca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 1 Jul 2015 08:22:03 +0200 Subject: [PATCH] Database.inTransaction --- GRDB/Database.swift | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) 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") + } + }