下面的函数返回一条Ledgers
记录。大多数时候,它会在可选_currentReceipt
变量中找到它,或者通过搜索数据库,不需要在那里写。我想使用只读的 GRDB 数据库连接。只读数据库连接可以在不同线程上并行运行。
在极少数情况下,前两个步骤失败,我可以创建一个默认分类帐。调用try FoodyDataStack.thisDataStack.dbPool.write { writeDB in ...
会抛出致命错误,数据库连接不可重入。我正在寻找一种方法来保存该默认分类帐,而不必将整个函数包装在读写连接中。
我可以在 GRDB .read 块中的单独队列上调用 NSOperation 吗?
class func getCurrentReceipt(db: Database) throws -> Ledgers {
if let cr = FoodyDataStack.thisDataStack._currentReceipt {
return cr
}
// Fall through
do {
if let cr = try Ledgers.filter(Ledgers.Columns.receiptClosed == ReceiptStatus.receiptOpen.rawValue).order(Ledgers.Columns.dateModified.desc).fetchOne(db) {
FoodyDataStack.thisDataStack._currentReceipt = cr
return cr
} else {
throw FoodyDataStack.myGRDBerrors.couldNotFindCurrentReceipt
}
} catch FoodyDataStack.myGRDBerrors.couldNotFindCurrentReceipt {
// Create new receipt with default store
let newReceipt = Ledgers()
newReceipt.dateCreated = Date()
newReceipt.dateModified = Date()
newReceipt.receiptStatus = .receiptOpen
newReceipt.receiptUrgency = .immediate
newReceipt.dateLedger = Date()
newReceipt.uuidStore = Stores.defaultStore(db).uuidKey
FoodyDataStack.thisDataStack._currentReceipt = newReceipt
return newReceipt
} catch {
NSLog("WARNING: Unhandled error in Ledgers.getCurrentReceipt() \(error.localizedDescription)")
}
}
编辑:我把这个问题留在这里,但我想我可能会进行过早的优化。我将尝试使用 dbQueue 而不是 dbPool,看看性能如何。如果速度需要,我会回到 dbPool。