Modify data
This chapter provides a detailed explanation and step-by-step guide for modifying data within an indexed composition in Inery.
Ensure that you are familiar with the indexed composition definitions and insertion methods covered in the Insert Data section.
Modifying data in a composition involves verifying if the target object exists within the indexed composition. If it exists, you can modify it using the modify method. Below are the key steps:
- Verify if the Object Exists: Use an iterator to check for the presence of the object.
- Modify the Object: Update the object using the
modifymethod if it is found in the indexed composition.
Find Record to Modify
Define logic for locating the record in the indexed composition. Add custom error handling if the record does not exist.
- Full Modify Action
- Find Action
- Modify Record
ACTION modify(name owner, uint64_t new_data) {
// Ensure that the action is authorized by the owner
require_auth(owner);
// Find the record by the owner's primary key
auto itr = container.find(owner.value);
check(itr != records.end(), "Error: Owner does not exist in the composition.");
// Modify the existing record with the new data
records.modify(itr, owner, [&](auto& row) {
row.data = new_data;
});
}
Compared to emplace action, modify requires 3 parameters: iterator, payer and lambda expression
itr- Itterator found fromfindmethod pointing to the ownerowner- Allocate memory used for this action[&](auto& row) {row.data = new_data;}- Set data record with new value
auto itr = container.find(owner.value);
// Custom error handling if owner does not exist
check(itr != container.end(), "Error: Owner does not exist in the composition.");
auto itr = container.find(owner.value)Define iterator for owner valueitr != container.end()Check whether iterator is not empty which implies that owner was found
container.modify(itr, _self, [&]( auto& u ) {
u.data = new_data; // Update the data field with new value
});
container.modify()is used to modify an existing record in the indexed composition.itris the iterator pointing to the record to modify._selfdenotes that the contract itself will pay for any RAM costs involved.auto& uprovides a reference to the record being modified.u.data = new_dataassigns the new data value to the existing record.
Add Custom Error Handling
Ensure that only valid modifications are made, and provide meaningful error messages to assist debugging.
check(new_data > 0, "Error: Data value must be greater than zero.");
check()ensures that the new data value is valid.new_data > 0checks that the data value is positive.- The error message helps identify incorrect input.