【问题标题】:Vapor Fluent Database transaction is not atomicVapor Fluent 数据库事务不是原子的
【发布时间】:2019-05-25 09:09:02
【问题描述】:

我正在创建一个database 事务,其中包含多个插入。结果保存为 Future 的 array。然后我在寻找do{..}.catch{..}构造中的运算结果。这是

问题:如果我从 do 块返回失败的未来,那么所有事务都会回滚 - 很好,但如果我从“catch”块返回相同的失败未来,那么一些记录正在提交到数据库。

    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 行(块 catch)中实现了失败,并且我遇到了未还原事务的问题。 但是,如果我注释掉第 1 行并取消注释第 2 行,那么 promise 在第 3 行中实现(块 do),并且整个事务被正确还原。

是我代码某处的错,还是 Fluent 错误?

【问题讨论】:

    标签: swift vapor


    【解决方案1】:

    我不确定您的示例代码中的构造,尤其是 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())
        }
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-09
      • 2019-07-27
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多