我正在创建一个数据库
事务,其中包含多个插入内容。结果保存为 Future 的数组
。然后我在 do{..}.catch{..}
构造中查找操作结果。这是
issue: if I'm returning failed future from do block then all transaction is rolling back - good, but if I'm returning the same failed future from "catch" block then some records are committing to the database.
func save(on req: Request) -> Future<Confirmation>
{
return req.transaction(on: .psql) { conn in
let promise = conn.eventLoop.newPromise(Confirmation.self)
var futures = [Future<Bool>]()
for i in 0 ..< 20
{
let g1 = Group()
g1.name = "\(i)"
let f1 = g1.save(on: conn).then { _ -> Future<Bool> in
if i == 15
{
// return conn.eventLoop.newSucceededFuture(result: false) //1
return conn.eventLoop.newFailedFuture(error: SyncError.nullPrimaryKey) // 2
}
else
{
return conn.eventLoop.newSucceededFuture(result: true)
}
}
futures.append(f1)
}
futures.do(on: conn){ results in
var res = true
results.forEach { e in
res = res && e
}
if res {
promise.succeed(result: Confirmation())
}
else {
promise.fail(error: SyncError.nullPrimaryKey) // 3
}
}.catch { e in
promise.fail(error: e) // 4
}
return promise.futureResult
}
}
}
在此示例中,promise 已履行,但在第 4 行( block catch)中失败,并且我遇到了未还原事务的问题。 但是,如果我注释掉第 1 行并取消注释第 2 行,则在第 3 行( block do)中实现 promise,并且整个事务将正确还原。
是我代码中某个地方的错误,还是 Fluent 的错误?
最佳答案
我不确定示例代码中的构造,尤其是 if i == 15
中的 SyncError.nullPrimaryKey
错误,但它看起来像下面的代码一样的
func save(_ req: Request) throws -> Future<Confirmation> {
return req.transaction(on: .psql) { conn in
return (0...15).map {
Group(name: $0)
}.map {
$0.save(on: conn).transform(to: ())
}.flatten(on: conn).transform(to: Confirmation())
}
}
希望对你有帮助
关于swift - Vapor Fluent 数据库事务不是原子的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56303381/