Last active
September 6, 2019 21:25
-
-
Save samalone/b93dbf8fd83e075ce8d71f0e57193b45 to your computer and use it in GitHub Desktop.
Transactions for Vapor 4 alpha 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import FluentPostgresDriver | |
| import FluentSQLiteDriver | |
| // This extension adds transaction support to the Database protocol. | |
| // It has to be specialized for each Database type used by your application, | |
| // since the Database protocol does not support the raw() method. | |
| extension Database { | |
| func transaction(callback: @escaping (Database) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> { | |
| return self.withConnection { (db) -> EventLoopFuture<Void> in | |
| switch db { | |
| case let db as SQLiteConnection: | |
| return db.raw("BEGIN TRANSACTION").run() | |
| .flatMap { callback(db) } | |
| .flatMap { db.raw("COMMIT").run() } | |
| .flatMapError { (err) in | |
| db.raw("ROLLBACK").run() | |
| .flatMap { () -> EventLoopFuture<Void> in | |
| return db.eventLoop.makeFailedFuture(err) | |
| } | |
| } | |
| case let db as PostgresConnection: | |
| return db.raw("BEGIN TRANSACTION").run() | |
| .flatMap { callback(db) } | |
| .flatMap { db.raw("COMMIT").run() } | |
| .flatMapError { (err) in | |
| db.raw("ROLLBACK").run() | |
| .flatMap { () -> EventLoopFuture<Void> in | |
| return db.eventLoop.makeFailedFuture(err) | |
| } | |
| } | |
| default: | |
| fatalError("Unsupported Database type for transaction: \(type(of: db))") | |
| // If you would prefer to forgo the safety of the transaction | |
| // and simply execute the callback, you can replace the fatalError with: | |
| // return callback(db) | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment