timshannon / badgerhold

BadgerHold is an embeddable NoSQL store for querying Go types built on Badger
MIT License
519 stars 51 forks source link

Urgent Info Needed: How to update some fields of the item/record in DB #100

Closed PD-Pramila closed 1 year ago

PD-Pramila commented 1 year ago

We have a use case, where we have one of the members in struct as reference count. Based on some business logic we want to increase/decrease the reference count. While updating the reference count, we dont have knowledge of values of other members of struct, which are stored in DB. We even don't know what was the prev reference count. Should we first get the value and then update it using TxUpdate/update. TxUpdate/Update already gets the value to check if it's there, it will be to costly to get a value 2 times, right? What is the best way to update or increase a vlaue of one struct memeber, without specifying the all data values?

I saw that, TxUpdate deletes the old value and it's indexes and then inserts the new record. I didn't see any code which is updating the existing value in DB. And it expects the complete struct as value.

Will it replace the existing values of struct members which were not specified?

timshannon commented 1 year ago

So, some testing on your own can determine this for you, but version handling is the same in any database. The value in memory in the application may be more than one version behind whats in the database. You need to either lookup the current records and apply or change, or pass around a record version which you increment on each change, then pass in the version of the record in memory as part of your criteria when selecting the record.

For example, if you have version 4 in the database, and in memory the last time you selected the record it was version 2, and you proceeded to try to update the record where key = your key and version == 2, the update will update 0 records, because version 2 no longer exists in the database, and you can report back to the user that they are looking at old data and refresh their screen. Or handle it seamlessly for them.

The difference with a badger backed database, compared to something more traditional with individual fields, is that the update completely replaces the entire record, not just a specific field, so it becomes even more important not to override the value complete from memory if it's not the version you think it is.