From dd1d737f0fcd9e040d16ec914ac2829473526a3e Mon Sep 17 00:00:00 2001 From: Jonathan Schleifer Date: Sun, 4 Oct 2020 01:28:44 +0000 Subject: [PATCH] Add -[transactionWithBlock:] FossilOrigin-Name: 1ecc15c9b801a9531314936f644a43a863fc7811768c7c257b409adad349d6e6 --- src/SL3Connection.h | 3 +++ src/SL3Connection.m | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/SL3Connection.h b/src/SL3Connection.h index 556ca9d..0d84332 100644 --- a/src/SL3Connection.h +++ b/src/SL3Connection.h @@ -44,6 +44,9 @@ OF_ASSUME_NONNULL_BEGIN flags: (int)flags OF_DESIGNATED_INITIALIZER; - (SL3PreparedStatement *)prepareStatement: (OFConstantString *)SQL; - (void)executeStatement: (OFConstantString *)SQL; +#ifdef OF_HAVE_BLOCKS +- (void)transactionWithBlock: (bool (^)(void))block; +#endif @end OF_ASSUME_NONNULL_END diff --git a/src/SL3Connection.m b/src/SL3Connection.m index ab07300..9d18789 100644 --- a/src/SL3Connection.m +++ b/src/SL3Connection.m @@ -90,4 +90,25 @@ exceptionWithConnection: self errorCode: code]; } + +#ifdef OF_HAVE_BLOCKS +- (void)transactionWithBlock: (bool (^)(void))block +{ + bool commit; + + [self executeStatement: @"BEGIN TRANSACTION"]; + + @try { + commit = block(); + } @catch (id e) { + [self executeStatement: @"ROLLBACK TRANSACTION"]; + @throw e; + } + + if (commit) + [self executeStatement: @"COMMIT TRANSACTION"]; + else + [self executeStatement: @"ROLLBACK TRANSACTION"]; +} +#endif @end