groue / GRDB.swift

A toolkit for SQLite databases, with a focus on application development
MIT License
6.61k stars 677 forks source link

When transaction updating multiple records in the database, if one of the records does not exist, it leads to update failure. #1527

Closed songzhiming closed 3 months ago

songzhiming commented 3 months ago

When transaction updating multiple records in the database, if one of the records does not exist, it leads to update failure.

What did you do?

transaction updating multiple records in the database

What did you expect to happen?

update success. like this

image

What happened instead?

update failure. error :"Key not found in table"

Environment

GRDB flavor(s):GRDB GRDB version:6.21.0 Installation method:CocoaPods Xcode version:Version 15.1 (15C65) Swift version:5.9 Platform(s) running GRDB:iOS **macOS version running Xcode:

Demo Project

this is my table ​ CREATE TABLE "QuantitySamples" ("dataId" INTEGER PRIMARY KEY, "quantity" REAL) ​ this is swift update ​ dbWriter.asyncWrite { db in for tmp in samples { let quantityTable = QuantityTable(dataId: rowId, quantity: self.quantity) try quantityTable.update(db) } } completion: { _, result in } ​

groue commented 3 months ago

Hello @songzhiming,

This is documented behavior, both in the README, and in the update method documentation. GRDB won't let your app think that an update was successful when nothing was actually updated.

If your app is OK with not updating anything, it has to be explicit, and catch this error:

do {
    try myRecord.update(db)
} catch RecordError.recordNotFound {
    // My record does not exist so we did not update anything.
    // This is OK because [insert your reason here].
}
songzhiming commented 3 months ago

@groue
Are you suggesting that I catch only the "recordNotFound" error and continue to throw other errors?

groue commented 3 months ago

Yes indeed. That's the way, in Swift, to provide a specific handling for a specific error.

songzhiming commented 3 months ago

@groue thank you very much