Skip to content

Instantly share code, notes, and snippets.

@samalone
Last active September 6, 2019 21:25
Show Gist options
  • Select an option

  • Save samalone/b93dbf8fd83e075ce8d71f0e57193b45 to your computer and use it in GitHub Desktop.

Select an option

Save samalone/b93dbf8fd83e075ce8d71f0e57193b45 to your computer and use it in GitHub Desktop.
Transactions for Vapor 4 alpha 3
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